我试图用一个朋友在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