Java随机生成器';种子产量不同
在尝试使用创建时传递到对象中的两个特定种子创建硬币对象类时,我注意到,当将种子传递到int“seed”时,seed变量生成的变量与仅将特定数字输入随机数生成器不同。下面是Coin类的一些代码:Java随机生成器';种子产量不同,java,random,numbers,generator,seed,Java,Random,Numbers,Generator,Seed,在尝试使用创建时传递到对象中的两个特定种子创建硬币对象类时,我注意到,当将种子传递到int“seed”时,seed变量生成的变量与仅将特定数字输入随机数生成器不同。下面是Coin类的一些代码: public int headCount; public int tailCount; public int seed; public Coin( int n ){ seed = n; headCount = 0; tailCount = 0; } public Random f
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 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 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 int headCount;
public int tailCount;
public int seed;
public Random flipGenerator = new Random(seed);
public Coin( int n ){
seed = n;
headCount = 0;
tailCount = 0;
}
在Java中,任何未显式初始化的字段都会被赋予一个0/null/false值,因此您总是执行
flipGenerator=new Random(0)
。在构造函数中初始化seed
时,已经创建了随机对象。实例字段是在构造函数之后声明的这一事实与此无关,因为所有实例字段及其初始化表达式都是在调用构造函数之前执行的。无论何时初始化Coin
类,它都将使用0作为种子。不管您是否将flipGenerator
初始化放在构造函数下面,它仍然会在构造函数中被调用,因为它是一个实例变量
Coin coin1 = new Coin( 17 );
Coin coin2 = new Coin( 13 );
此代码使用0,因为在传递种子时,flipGenerator已使用默认种子0初始化
你需要这样做
public int headCount;
public int tailCount;
public int seed;
public Random flipGenerator;
public Coin( int n ){
seed = n;
headCount = 0;
tailCount = 0;
flipGenerator = new Random(seed);
}
...
}
什么构成“不正确”?但是,您是否尝试过在调试器中运行并查看变量的初始化?如果将flipGenerator移动到构造函数中会发生什么?
public int headCount;
public int tailCount;
public int seed;
public Random flipGenerator;
public Coin( int n ){
seed = n;
headCount = 0;
tailCount = 0;
flipGenerator = new Random(seed);
}
...
}