【发布时间】: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");
首先,它一直告诉我必须初始化dice1 和dice2,但我不明白为什么。但更重要的是,我知道这不可能是正确的,但我只是不确定如何编写同时掷两个骰子然后在它们同时为 1 时计数的代码。
另外,我尝试将它们放在同一个循环中。这可能吗?
【问题讨论】:
-
附注:在“真实”代码中,我基本上从不使用
Math.random。原因是:这是不可预测的。是的,这听起来像是故意的,但对于测试和调试、结果的可再现性等,可预测的行为是必不可少的。相反,您应该使用java.util.Random:在开始时创建一个实例Random random = new Random(0);,然后使用它。它还有一个直接给你一个整数的方法:int dice = random.nextInt(6) + 1。
标签: java