【发布时间】:2017-08-05 05:04:58
【问题描述】:
在尝试使用创建时传递给对象的两个特定种子创建 Coin 对象类时,我注意到当将种子传递给 int“种子”时,种子变量产生的变量与仅输入特定的不同数进入随机数发生器。下面是 Coin 类的一些代码:
public int headCount;
public int tailCount;
public int seed;
public Coin( int n ){
seed = n;
headCount = 0;
tailCount = 0;
}
public Random flipGenerator = new Random(seed);
public String flip(){
String heads = "H";
String tails = "T";
boolean nextFlip = flipGenerator.nextBoolean();
if (nextFlip == true)
{
headCount++;
return heads;
}
if (nextFlip == false)
{
tailCount++;
return tails;
}
return null;
}
以下是创建和打印 Coin 对象的文件:
Coin coin1 = new Coin( 17 );
Coin coin2 = new Coin( 13 );
该文件中的代码使用 17 种子打印 20 次随机翻转的结果,使用 13 种子打印 10 次,最后再次使用 17 种子打印 35 次。但是使用时输出不正确
public Random flipGenerator = new Random(seed);
相对
public Random flipGenerator = new Random(17);
或
public Random flipGenerator = new Random(13);
为什么会这样?
【问题讨论】:
-
什么是“不正确”?但是,您是否尝试过在调试器中运行并查看变量的初始化?如果你将 FlipGenerator 移到构造函数中会发生什么?
标签: java random numbers generator seed