[英]Generating random numbers giving the same number each time
我的作業:
通過公式
𝑟𝑛𝑒𝑤 = (𝑎 ⋅ 𝑟𝑜𝑙𝑑 + 𝑏)%𝑚
一個簡單的隨機發生器。 然后,通過將𝑟𝑜𝑙𝑑
設置為𝑟𝑛𝑒𝑤
並重復該過程,可以生成新的“隨機”數字。 編寫一個方法,要求用戶輸入𝑟𝑜𝑙𝑑,𝑎,𝑏和value的值。 您的方法應返回一個整數數組,其中包含此公式生成的前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
有人可以幫我解決問題嗎?
將數組傳遞給System.out.println()
將打印出數組的“內存地址”。 您可以使用Arrays.toString()
獲得格式正確的數組內容String
:
System.out.println(Arrays.toString(random(r,a,b,m)));
相反,根據分配要求,應將r更新為新生成的隨機數,並使用它生成下一個隨機數!
System.out.println(numberArray)
看到這個了更多的解釋。 供你參考:
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]);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.