【问题标题】:Simulating rolling two dice java and see if the results are `1,1`模拟掷两个骰子java,看看结果是不是'1,1'
【发布时间】:2019-08-25 08:22:23
【问题描述】:

这是我的作业问题,在 Java 中: 编写一个程序,模拟掷 2 个骰子 20 次。程序输出每对结果并计算并输出结果为1, 1 的次数。

我已尝试运行此代码,但遇到了问题。这是我的代码:

Scanner in = new Scanner(System.in);
int dice1, dice2, i, j, countOneOne;
countOneOne = 0;
// dice1 = 0;
// dice2 = 0;

for (j = 1;j <= 5; j++) {
    dice1 = 1 +(int) (Math.random() * 6); 
    j = dice1;
    System.out.println("Result of dice1: " + dice1);
} 
for (i = 1; i <= 5; i++) {
    dice2 = 1 +(int)(Math.random()*6);
    i = dice2;
    System.out.println("Result of dice2: " + dice2);
}

System.out.println("Result of dice1: " + dice1 + " ; Result of dice2: " + die2);   

if (dice1 == 1 && dice2 == 1) countOneOne++;

System.out.println(countOneOne + " is the number of 1, 1 results");

首先,它一直告诉我必须初始化dice1dice2,但我不明白为什么。但更重要的是,我知道这不可能是正确的,但我只是不确定如何编写同时掷两个骰子然后在它们同时为 1 时计数的代码。

另外,我尝试将它们放在同一个循环中。这可能吗?

【问题讨论】:

  • 附注:在“真实”代码中,我基本上从不使用Math.random。原因是:这是不可预测的。是的,这听起来像是故意的,但对于测试和调试、结果的可再现性等,可预测的行为是必不可少的。相反,您应该使用java.util.Random:在开始时创建一个实例Random random = new Random(0);,然后使用它。它还有一个直接给你一个整数的方法:int dice = random.nextInt(6) + 1

标签: java


【解决方案1】:

您的代码有点偏离,当使用Math.random() * 6 时,您将获得一个范围在05 的值(您需要添加一个)。此外,如果您将掷骰子的逻辑提取到方法中,则逻辑要简单得多。类似的,

public static int rollDie(int sides) {
    return (int) (Math.random() * sides) + 1;
}

然后你想实现你的方法。循环二十次,掷两个骰子。计算蛇眼的数量并打印滚动结果。喜欢,

public static void main(String[] args) throws Exception {
    int snakeEyes = 0;
    // Twenty times
    for (int i = 0; i < 20; i++) {
        // Roll two dice
        int die1 = rollDie(6), die2 = rollDie(6);

        // Count snake eyes.
        if (die1 == 1 && die2 == 1) {
            snakeEyes++;
        }

        // Display roll results.
        System.out.printf("Result of die1: %d ; Result of die2: %d%n", die1, die2);
    }
    System.out.printf("%d is the number of 1,1 results%n", snakeEyes);
}

【讨论】:

  • 呃,你的答案比我好。刚要发帖。好吧,赞成,因为它有效:)
猜你喜欢
  • 1970-01-01
  • 2017-03-24
  • 2011-07-12
  • 2013-11-28
  • 1970-01-01
  • 2018-01-03
  • 2019-03-09
  • 1970-01-01
相关资源
最近更新 更多