【问题标题】:Java Random Generator's seed producing different outputsJava Random Generator 的种子产生不同的输出
【发布时间】: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


【解决方案1】:

在调用构造函数之前初始化实例字段。

按照执行顺序,这段代码:

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 中,任何未显式初始化的字段都被赋予零/null/false 值,因此您总是执行flipGenerator = new Random(0)。当您在构造函数中初始化 seed 时,已经创建了 Random 对象。实例字段在构造函数之后声明的事实是无关紧要的,因为所有实例字段及其初始化表达式都是在调用构造函数之前执行的。

【讨论】:

    【解决方案2】:

    每当您初始化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);
        }
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 2019-04-30
      • 1970-01-01
      • 1970-01-01
      • 2014-05-06
      • 2014-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-21
      相关资源
      最近更新 更多