我的任务:
通过公式
= ( ⋅ + )%
获得简单的随机生成器。然后通过设置生成新的“随机”数字到
并重复此过程。写一个方法 要求用户输入,和的值。您的 方法应返回包含前25个的整数数组 此公式生成的“随机”值。
到目前为止,这是我所拥有的,但由于某种原因我的代码不打印随机25个数字的数组
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;
}
这就是印刷:
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
有人可以帮我解决问题吗?
答案 0 :(得分:1)
将数组传递给System.out.println()
将打印出&#34;内存地址&#34;数组。您可以使用Arrays.toString()
来获取格式内容格式良好的String
:
System.out.println(Arrays.toString(random(r,a,b,m)));
答案 1 :(得分:1)
相反,根据分配要求,您应该将r更新为新生成的随机数,并使用它来生成下一个随机数!
System.out.println(numberArray)
,有关详细说明,请参阅this。供您参考:
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]);
}
}