Reputation: 3
My assignment:
A simple random generator is obtained by the formula
ππππ€ = (π β ππππ + π)%π
. New βrandomβ numbers are then generated by settingππππ
toππππ€
and repeating the process. Write a method that asks the user to enter a value for ππππ, π, π and π. Your method should return an array of integers that contain the first 25 βrandomβ values generated by this formula.
So far this is what I have, but for some reason my code is not printing the array of random 25 numbers
public static void main(String[] args){
Scanner theInput = new Scanner(System.in);
System.out.println("Enter a value for r: ");
int r = theInput.nextInt();
System.out.println("Enter a value for a: ");
int a = theInput.nextInt();
System.out.println("Enter a value for b: ");
int b = theInput.nextInt();
System.out.println("Enter a value for m: ");
int m = theInput.nextInt();
System.out.println(random(r,a,b,m));
}
public static int[] random(int r, int a, int b, int m){
String num = "";
int numberArray[] = new int [25];
for (int i = 0; i < numberArray.length; i++) {
int answer = (a*r+b)%m;
numberArray [i] = answer;
}
for(int i=0;i<numberArray.length;i++){
System.out.println(numberArray[i]);
}
System.out.println();
return numberArray;
}
This is what is printing:
258
258
258
258
258
258
258
258
258
258
258
258
258
258
258
258
258
258
258
258
258
258
258
258
258
[I@55f96302
Can someone help me to fix the problem?
Upvotes: 0
Views: 742
Reputation: 2334
Instead, according to the assignment requirements, you should update the r as the newly generated random number and use it to generate the next random number!
System.out.println(numberArray)
, see this for more explanation.For your reference:
public static int[] random(int r, int a, int b, int m) {
String num = "";
int numberArray[] = new int [25];
for (int i = 0; i < numberArray.length; i++) {
int answer = (a * r + b) % m;
numberArray [i] = answer;
r = answer; // you should set r as the answer and use it for the next random number
}
return numberArray;
}
public static void main(String[] args) {
Scanner theInput = new Scanner(System.in);
System.out.println("Enter a value for r: ");
int r = theInput.nextInt();
System.out.println("Enter a value for a: ");
int a = theInput.nextInt();
System.out.println("Enter a value for b: ");
int b = theInput.nextInt();
System.out.println("Enter a value for m: ");
int m = theInput.nextInt();
int[] numberArray = random(r, a, b, m);
for(int i = 0; i < numberArray.length; i++){
System.out.println(numberArray[i]);
}
}
Upvotes: 1
Reputation: 1106
Passing an array to System.out.println()
will print out the "memory address" of the array. You can use Arrays.toString()
to get a nicely formatted String
of the array contents:
System.out.println(Arrays.toString(random(r,a,b,m)));
Upvotes: 1