Why is the output remaining the same? - java

import java.io.*;
public class TestCaseAbcd {
public static void main(String args[]) throws IOException {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(
float x0;
float a, c, mod;
int num, ch = 0;
double[] rNumbers;
double[] rTemp;
System.out.println("Enter the SEED value: ");
System.out.println("x0 ");
x0 = Float.parseFloat(stdin.readLine());
System.out.println("Enter the multiplier's value:");
System.out.println("a: ");
a = Float.parseFloat(stdin.readLine());
System.out.println("Enter the value of increment c and modulus m: ");
System.out.println("c: ");
c = Float.parseFloat(stdin.readLine());
System.out.println("m: ");
mod = Integer.parseInt(stdin.readLine());
System.out.println("How many random nunbers u need? ");
num = Integer.parseInt(stdin.readLine());
rNUmbers = new double[num];
rTemp = new double[rNumbers.length];
rTemp[0] = x0;
for (int i = 0; i < num; i++)
{
if(i + 1 != num)
{
rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
}
else
{
break;
}
}
for (int i = 0; i < rNumbers.length; i++)
{
if (i + 1 != num)
{
rNumbers[i] = rTemp[i] / mod;
}
else
{
break;
}
}
System.out.println("The PSEUDO random numbers are: ");
for (int i = 0; i < rNumbers.length; i++)
{
System.out.println(rNumbers[i]);
}
double firstNum = rNumbers[0];
System.out.println("1. Select Mutant 1 ");
System.out.println("2. Select Mutant 2 ");
System.out.println("3. Exit ");
}
}
In the above code, the expected output should start from: 0.68.
But, instead it started from:
0.37.
In fact, even after I changed the following code:
rTemp[i+1] = ( ( (rTemp[i]*a) + c ) % mod);
to:
rTemp[i+1] = ( ( (rTemp[i]/a) + c ) % mod);
The output still started from 0.37.
The input values are:
x0 = 37
a = 7
c = 9
m = 100
Please help me in analyzing the code so as that the output shouldn't start with 0.37.
Summary of the problem: the code is producing the same number i.e. 0.37 no matter what the equation stated above in the code is modified to.

You're setting the first value in rTemp to 37, then you start printing from the first value. It only makes sense that the first value printed would be 0.37.
x0 = 37
mod = 100
...
rTemp[0] = x0;
...
rNumbers[i] = rTemp[i] / mod;
...
System.out.println(rNumbers[i]);
To achieve the output you're looking for, change this:
rTemp[0] = x0;
for (int i = 0; i < num; i++)
{
if(i + 1 != num)
{
rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
}
else
{
break;
}
}
to this:
rTemp[0] = (((x0 * a) + c) % mod);
for (int i = 0; i < num-1; i++)
{
rTemp[i + 1] = (((rTemp[i] * a) + c) % mod);
}
On a side note, if all you really want is an array of psudo-random doubles, it's easier to do something like this:
Random rnd = new Random(seed);
double[] rNumbers = new double[num];
for(int i = 0; i < num; i++)
rNumbers[i] = (double)rnd.nextInt(100) / 100;
For any given seed, you'll get the same array of doubles every time.

Related

Java "For" loop output repeats

I am a beginner trying to program a java code to produce output numbers that is a prime factor of two and five.
For example, if input is 8, then output should be 2 4 5 8.
However, whenever I print my output, the result will be 2 5 4 5 8 5.
Please advice on where I have gone wrong.
Thank you
import java.util.Scanner;
class twofive {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter n:");
int n = sc.nextInt();
double num = 0;
double num2 = 0;
for (int i = 1; (((Math.pow(2,i))<= n) || ((Math.pow(5,i)) <=n) || (((Math.pow(2,i))<= n) && ((Math.pow(5,i)) <=n))) ; i++) {
if (( Math.pow(2,i)) <= n)
num = (Math.pow(2,i));
int convert = (int) num;{
System.out.print(convert + " ");
}
if ((Math.pow(5,i)) <= n)
num2 = (Math.pow(5,i));
int convert2 = (int) num2;
{System.out.print(convert2 + " ");
}
}
}
}
After you review #AmedeeVanGasse 's comment, you need to fix your braces.
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter n:");
int n = sc.nextInt();
double num = 0;
double num2 = 0;
for (int i = 1; Math.pow(2,i))<= n) || ((Math.pow(5,i)) <=n) || (((Math.pow(2,i))<= n) && ((Math.pow(5,i)) <=n))) ; i++) {
if (( Math.pow(2,i)) <= n) {
num = (Math.pow(2,i));
int convert = (int) num;
System.out.print(convert + " ");
}
if ((Math.pow(5,i)) <= n) {
num2 = (Math.pow(5,i));
int convert2 = (int) num2;
System.out.print(convert2 + " ");
}
}
}
You should also review the logic in your for loop and if statements. They are full of unneeded redundancies.

How do I add power in java?

I am new to Java and stackoverflow. I am writing a program that can add power in Java, for example: 2^1, 2^1+2^2, 2^1+2^2+2^3,.. so on.
I have written below program and I don't know what I am doing wrong when I am trying to add the powers. I just get 2^1 2^2 2^3,... as output. I hope you get the idea from my code and it will be a great help if you guys can help me learn.
Thank you in advance!
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter b: ");
int b = sc.nextInt(); //b = second number
System.out.print("Enter t: ");
int t = sc.nextInt(); //t = no. of iterations
int x=0, sum = 0;
for (int i = 0; i < t;) {
for (int j = 0; j < t; j++) {
int pow = (int) Math.pow(2, i);
x = a + (pow * b);
i++;
System.out.printf("%d ", x);
sum = x;
}
sum = x + sum;
System.out.println(sum);
}
}
According to Mathematics rules, if it is addition among the numbers, for example 2^1 + 2^2 + 2^3 + 2^4... Then it is simple you don't need two loops and the t variable. You just need the base and the last exponent limit.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the base: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter iterations: ");
int b = sc.nextInt(); //b = No of iterations
int sum = 0;
for (int i = 1; i <= b; i++) {
sum += Math.pow(a, i);
}
System.out.println("The sum is " + sum);
}
But if there is multiplication among the numbers, then you will add the exponents if the base is same. Fox example 2^1 * 2^2 * 2^3 * 2^4.... Then you may do it as below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the base: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter iterations: ");
int b = sc.nextInt(); //b = No of iterations
Double res;
int powerSum = 0;
for (int i = 1; i <= b; i++) {
powerSum += i;
}
System.out.println("Power sum is " + powerSum);
res = Math.pow(a, powerSum);
System.out.println("The result is " + res);
}
In your inner loop
int pow = (int) Math.pow(2, i);
shouldn't you be using j instead of i?
Very simply you can do it as below:
public static int getPow(int num, int pow) {
if (pow < 2) {
return num;
}
return (int) Math.pow(num, pow) + getPow(num, --pow);
}
Usage:
int pow = getPow(2, 4);// 2*1 + 2*2 + 2*2*2 + 2*2*2*2 = 2+4+8+16 = 30
System.out.println("pow = " + pow);
And Result:
pow = 30

What's wrong with my for-loop?

I am trying to print each digit of an integer and then sum of each digit like this. There is something wrong with the loops but I cant seem to figure it out. I want it to be like this:
Please enter a number: 194
1 * 100 = 100
9 * 10 = 90
4 * 1 = 4
import java.util.Scanner;
public class PrintEachDigits {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = scan.nextInt();
String s = ""+num;
double d = 0;
for(int i = 0; i < s.length(); i++) {
for(int j = s.length()-1; j >= 0; j--) {
d = Math.pow(10,j);
System.out.println(s.charAt(i) + " * " + d
+ " = " + (s.charAt(i)*d));
}
}
}
}
This is the output of my code:
Enter the number: 194
1 * 100.0 = 4900.0
1 * 10.0 = 490.0
1 * 1.0 = 49.0
9 * 100.0 = 5700.0
9 * 10.0 = 570.0
9 * 1.0 = 57.0
4 * 100.0 = 5200.0
4 * 10.0 = 520.0
4 * 1.0 = 52.0
There's a couple problems with your code.
The first problem is that you don't need two loops, you just need one.
The second problem is confusing chars and ints. '0' is not the same as 0; instead, '0' is a numeric value representing the encoding of that character (which turns out to be 48). So to get the correct value that you want, you should subtract '0' from the char before doing your math.
for(int i = 0; i < s.length(); i++) {
d = Math.pow(10, s.length() - i - 1);
int value = s.charAt(i) - '0';
System.out.println(value + " * " + d
+ " = " + (value*d));
}
This will get it close to the output you wanted. It's still showing the .0 at the end though, because d is a double. Make it an int to fix that.
//This can be scoped to inside the loop, so you don't need to declare it beforehand
int d = (int)Math.pow(10,j);
import java.util.Scanner;
public class PrintEachDigits {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = scan.nextInt();
String s = "" + num;
int len = s.length() - 1;
long d = 0;
if (len < 2) {
d = 1;//For single digit
} else {
d = (long)Math.pow(10, len);
}
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i) + " * " + d + " = "
+ ((s.charAt(i) - '0') * d));
d = d / 10;
}
}
}

String index out of range (Repeating Sequence of digits)

I seem to be having a problem with my code which is to look for the repeating sequence of digits. I have converted(?) double to string because I get the error unreachable statement. (which I guess helps to looking for the reason why I get the error I have now?).
Whenever I run it, it goes fine until I finish entering N and D.
It'll say "Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 3"
Here is my code below:
import java.util.*;
public class RepeatingSequence{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter N,D: ");
int numerator = in.nextInt();
int denominator = in.nextInt();
double quotient = numerator / denominator;
String number = "" + quotient;
char n = number.charAt(0);
int j = 1;
int z = 0;
String output = "";
char[] index = number.toCharArray();
for ( int i = 2; number.charAt(j) != number.charAt(i); i++ ){
index[z] = number.charAt(z);
index[j] = number.charAt(j);
index[i] = number.charAt(i);
output = output + index[i];
if ( index[i] != index[z] ){
System.out.print(index[z] + ".(" + index[j] + output + ")");
}
}
}
}
just add i < number.length() to the condition
( int i = 2; i < number.length() && number.charAt(j) != number.charAt(i); i++ )
For your exception, I think you should write safer code - something on the lines of:
int len = number.length();
for ( int i = 2; (i < len) && (j < len) &&
number.charAt(j) != number.charAt(i); i++ ){
...
}
I am not attempting to solve the problem that you are trying to solve but just the problem you are facing. Sorry for that.
I changed your code a little bit try it out and see what you think:
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter N,D: ");
double numerator = in.nextDouble();
double denominator = in.nextDouble();
double quotient = numerator / denominator;
String number = "" + quotient;
char n = number.charAt(0);
int j = 1;
int z = 0;
String output = "";
char[] index = number.toCharArray();
int max = -1;
int currentNumber = -1;
int temp = -1;
int tempMax = -1;
System.out.println("" + quotient);
boolean check = true;
for(int i = (number.indexOf(".") + 1); i < index.length; i++)
{
if(max == -1)
{
currentNumber = i;
temp = i;
max = 1;
tempMax = 1;
}
else
{
if(index[i] == index[i-1])
{
tempMax++;
}
else
{
if(tempMax > max)
{
check = false;
max = tempMax;
currentNumber = temp;
}
tempMax = 1;
temp = i;
}
}
}
if(check)
{
max = tempMax;
}
System.out.println(index[currentNumber] + " repeats " + max + " times.");
}
Example of input/output:
Enter N,D: 1
3
0.3333333333333333
3 repeats 16 times.

ArrayOutOfBoundsException with Base Conversion

For my program, I am trying to convert a number from a base to another a base. However, I am trying to figure out why I keep getting the ArrayOutOfBoundsException. Can anyone help? I am using 21 as the number, 10 as the original base, and then 2 as the new base.
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//Enter original number
System.out.println("Enter a number: ");
Double num = input.nextDouble();
String orgNum = String.valueOf(num);
//Enter original base
System.out.println("Enter its base: ");
int b = input.nextInt();
//Enter new base
System.out.println("Enter base to be converted to: ");
int a = input.nextInt();
input.close();
//Conversion
String newNum = convertBase(orgNum, b, a);
//New number
System.out.println("New Number: " + newNum);
}
public static String convertBase(String orgNum, int b, int a)
{
double value = 0;
double decDigit = 0;
char chDigit;
int length = orgNum.length();
for (int p = 0; p < length; p ++)
{
chDigit = Character.toUpperCase(orgNum.charAt(length - 1 - p));
if(Character.isLetter(chDigit))
{
decDigit = chDigit - 'A' + 10;
}
else if (Character.isDigit(chDigit))
{
decDigit = chDigit - '0';
}
else
{
System.out.println("ERROR: Digit is unrecognizable.");
}
value += decDigit + Math.pow(b, p);
}
int D = 1;
for (D = 1; Math.pow(a, D) <= value; D++) {}
char[] newNum = new char[D];
double pwr;
for (int p = D - 1; p >= 0; D--)
{
pwr = Math.pow(a, p);
decDigit = Math.floor(value / pwr);
value -= decDigit*pwr;
if (decDigit <= 9)
{
newNum[D - 1 - p] = (char) ('0' + (int)decDigit);
}
else
{
newNum[D - 1 - p] = (char) ('0' + (int)decDigit - 10);
}
}
return new String(newNum);
}
There are two simple errors I've seen on your code,
a) You should use nextInt instead of nextDouble, and store the value in an primitive integer type;
//Enter original number
System.out.println("Enter a number: ");
//Double num = input.nextDouble();
int num = input.nextInt();
String orgNum = String.valueOf(num);
b) Instead of D, you should decrement p here;
double pwr;
// for (int p = D - 1; p >= 0; D--)
for (int p = D - 1; p >= 0; p--)
{
I didn't check that if the output is valid or not, but the modified version below is working fine;
import java.util.Scanner;
public class Test {
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
//Enter original number
System.out.println("Enter a number: ");
// Double num = input.nextDouble(); // #1: Convert to primitive integer
int num = input.nextInt();
String orgNum = String.valueOf(num);
//Enter original base
System.out.println("Enter its base: ");
int b = input.nextInt();
//Enter new base
System.out.println("Enter base to be converted to: ");
int a = input.nextInt();
input.close();
//Conversion
String newNum = convertBase(orgNum, b, a);
//New number
System.out.println("New Number: " + newNum);
}
public static String convertBase(String orgNum, int b, int a)
{
double value = 0;
double decDigit = 0;
char chDigit;
int length = orgNum.length();
for (int p = 0; p < length; p ++)
{
chDigit = Character.toUpperCase(orgNum.charAt(length - 1 - p));
if(Character.isLetter(chDigit))
{
decDigit = chDigit - 'A' + 10;
}
else if (Character.isDigit(chDigit))
{
decDigit = chDigit - '0';
}
else
{
System.out.println("ERROR: Digit is unrecognizable.");
}
value += decDigit + Math.pow(b, p);
}
int D = 1;
for (D = 1; Math.pow(a, D) <= value; D++) {}
char[] newNum = new char[D];
double pwr;
// for (int p = D - 1; p >= 0; D--) // #2: decrement the index p
for (int p = D - 1; p >= 0; p--)
{
pwr = Math.pow(a, p);
decDigit = Math.floor(value / pwr);
value -= decDigit*pwr;
if (decDigit <= 9)
{
newNum[D - 1 - p] = (char) ('0' + (int)decDigit);
}
else
{
newNum[D - 1 - p] = (char) ('0' + (int)decDigit - 10);
}
}
return new String(newNum);
}
}

Categories