【问题标题】:Random generator not appearing to generate certain numbers: is my code wrong or is it a feature of objects of type Random?随机生成器似乎没有生成某些数字:我的代码是错误的还是随机类型对象的特征?
【发布时间】:2023-03-03 21:07:02
【问题描述】:

我正在尝试编写一个模拟骰子游戏的方法,其中骰子(值从 1 到 6)被掷出四次,如果至少掷出一个 6,则返回 true,否则返回 false。如果返回 true,则游戏“获胜”。

我声明了两个变量来跟踪“6”被抛出的次数,另一个变量来跟踪游戏是否获胜(即是否抛出 6)。

然后我使用 for 循环来模拟掷骰子;如果掷出 6,这会增加掷出 6 的数量。

然后我使用条件返回 true,如果抛出了 6,否则返回 false。

我希望如果我运行代码足够多次,那么至少在某些情况下会返回 true(即我会“赢得”游戏)。 然而,当我实际运行代码时,我只会得到 false 返回。

我做错了什么?

这是我的代码:

     import java.util.Random;

     public class DiceGame {
Random generator;

public DiceGame() {   
    generator = new Random(45);
}

/** 
 * Throw a die four times and bet on at least one 6. 
 * @return true if the chevalier wins. 
 */
public boolean game1()  {
    int trueDice = 0; 
    boolean gameWon = false; 

    for (int i=0; i < 4;i++)  {
    int dieRoll = generator.nextInt(6);
    if (dieRoll == 6)  {
        trueDice++;
        }
      }

    if (trueDice >= 1)  {
            gameWon = true;
       } else {
           gameWon = false;
        }
    return gameWon; 
}

提前感谢您的帮助。

【问题讨论】:

    标签: java


    【解决方案1】:

    nextInt 为您提供一个介于 0(包括)和指定值(不包括)之间的数字。 因此,目前您正在生成 0-5 范围内的随机数。 将其更改为:

    int dieRoll = generator.nextInt(6) + 1;
    

    你会得到 1-6 的数字。

    【讨论】:

    • 谢谢!就这样解决了
    【解决方案2】:

    播种你的Random generator,如下所示:

    generator = new Random(System.currentTimeMillis());
    

    45 没有任何问题,但时间种子是消除程序中可预测性的更好选择。

    那么对于线路:int dieRoll = generator.nextInt(6);,应该是:

    int dieRoll = 1 + generator.nextInt(6);
    

    【讨论】:

    • 无参数构造函数将使用a value very likely to be distinct from any other invocation of this constructor.为随机播种
    • 是的,同样,OP 使用45 的值来初始化他的代码,使得程序的每次运行都非常可预测。顺便说一句,no args 构造函数使用System.nanoTime() 调用来播种自己。
    • 既然使用currentTimeMillis比省略参数更糟糕,那么包含它有什么意义呢?
    • 技术上System.currentTimeMillis()System.nanoTime() 快得多。不相信我?那么请阅读:NanoTime slower than CurrentTimeMillisDrift between CurrentTimeMillis and NanoTime。这就是为什么我更喜欢System.currentTimeMillis()。另一个好处是保证永远不会重复相同的值。
    猜你喜欢
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-14
    • 2016-02-16
    相关资源
    最近更新 更多