我試圖用一個朋友在Java中解釋隨機數發生器,當他每次運行該程序時都會得到相同的數字。我創建了自己的更簡單的版本,並且每次運行該程序時都會得到相同的確切數字。Java隨機數不是隨機的嗎?
我在做什麼錯?
import java.util.*;
public class TestCode{
public static void main(String[] args){
int sum = 0;
Random rand = new Random(100);
for(int x = 0; x < 100; x++){
int num = (rand.nextInt(100)) + 1;
sum += num;
System.out.println("Random number:" + num);
}
//value never changes with repeated program executions.
System.out.println("Sum: " + sum);
}
}
最後五個號碼的開出的100元是:
40
60
27
56
53
,我認爲是更好的方式使用的Math.random()。 – Gere 2013-04-29 23:48:51
你在創建你的Random實例時使用了一個常數種子。所以當然你會得到相同的數字。 – 2013-04-29 23:51:22
@Gere:'Math.random()'有什麼神奇之處,爲什麼它比使用Random實例更好? – 2013-04-29 23:51:59