0
這是我的代碼,我不斷收到輸出是:隨機數發生器總是在for循環中生成相同的數字?
Number is:54
Number is:54
.
.
.
Number is:54
Number is:54
Number is:54
Number is:54
Process completed.
代碼:
import java.util.Random;
public class random {
private static Random call = new Random();
private static int numb = call.nextInt(75) + 1;
public static void main(String[] args) {
for(int i = 0; i < 50; i++){
if (numb < 16) {
System.out.println("Number is:" + numb);
} else if (numb < 31 && numb > 15) {
System.out.println("Number is:" + numb);
} else if (numb < 46 && numb > 30) {
System.out.println("Number is:" + numb);
} else if (numb < 61 && numb > 45) {
System.out.println("Number is:" + numb);
} else {
System.out.println("Number is:" + numb);
}
}
}
}
是有辦法解決的代碼沒有把
private static Random call = new Random();
private static int numb = call.nextInt(75) + 1;
在主要代碼? (表示沒有創建new Random()
及其在主代碼中生成的數字)
原因是我還需要將int「麻木」傳遞給其他類,它們必須是相同的參數。如果我只是堅持 numb = call.nextInt(75)+ 1; 在主類的for循環中。當然它會起作用,但是「麻木」的參數在每一個班級都會有所不同。
謝謝!
只是要小心,每個線程使用不同的隨機實例或你可能會發現你的隨機數是...少一些。 – sirbrialliance
@sirbrialliance。我明白了,謝謝。但我還需要我創建其他類「發麻」,並且它必須是相同的數作爲「發麻」在主類,如果我添加麻木= call.nextInt(75)+ 1;在主類的for循環中,兩個「麻木」會有所不同,我如何使它們相同? – HayleyL
@Wil哈通感謝您的幫助,但我應該做的,如果我需要其他類的麻木價值? – HayleyL