【发布时间】:2016-03-07 16:37:18
【问题描述】:
我是一名初学者,通过在线资源自学 Java。我遇到过这个练习。
编写一个程序,通过从 1-6 中选择一个随机数,然后从 1-6 中选择第二个随机数来模拟掷骰子。将两个值相加,并显示总数。修改你的骰子游戏,让它一直滚动,直到它们得到双倍(两个骰子上的数字相同)。
到目前为止我有这个代码:
public class DiceGame {
public static void main(String[] args) {
System.out.println("ROLL THE DICE!\n");
int firstRoll = 1 + (int) (Math.random() * 6);
int secondRoll = 1 + (int) (Math.random() * 6);
while (firstRoll != secondRoll) {
System.out.println("Roll #1: " + firstRoll);
System.out.println("Roll #2: " + secondRoll);
int total = firstRoll + secondRoll;
System.out.println("The total is " + total);
}
System.out.println("You rolled doubles!");
System.out.println("Roll #1: " + firstRoll);
System.out.println("Roll #2: " + secondRoll);
int total = firstRoll + secondRoll;
System.out.println("The total is " + total);
}
}
问题是,当我运行此代码时,如果两个滚动不同,程序将永远运行,输出相同的第一个和第二个滚动值和总数...我确定我有一个逻辑错误while 循环。请帮忙。
这是我的输出示例:
Roll #1: 2
Roll #2: 3
The total is 5
Roll #1: 2
Roll #2: 3
The total is 5
Roll #1: 2
Roll #2: 3
The total is 5
Roll #1: 2
Roll #2: 3
The total is 5
Roll #1: 2
Roll #2: 3
The total is 5
Roll #1: 2
Roll #2: 3
The total is 5
Roll #1: 2
Roll #2: 3
The total is 5
Roll #1: 2
Roll #2: 3
The total is 5
Roll #1: 2
Roll #2: 3
The total is 5
(while 条件不断返回 false 并打印相同的值)
以下是所需输出的示例:
Roll #1: 3
Roll #2: 5
The total is 8
Roll #1: 6
Roll #2: 1
The total is 7
Roll #1: 2
Roll #2: 5
The total is 7
Roll #1: 1
Roll #2: 1
The total is 2
(程序应该在滚动双打时结束)
【问题讨论】:
-
如果骰子不相等(在您的 while 循环中),您需要“重新滚动”骰子,目前您只需将它们无限加在一起,而不更改两个“角色”的值
-
把 firstRoll = 1 + (int) (Math.random() * 6); secondRoll = 1 + (int) (Math.random() * 6);作为你在 while 循环中的最后一条语句
-
很明显,你两次得到同一对的概率是 1/36,当你掷出 3 对时,这个概率是天文数字的无穷小。您应该打开一个调试器来查看控制流。这称为
debugging。自己学习调试,你就像魔术师一样,自己回答问题。要求在 SO 调试您的程序是一种应受谴责的做法。此外,经验法则是消除代码中的重复项(google DRY 原则)。您将常见的代码段排除在外(我看到 println("Roll 1,2") 重复了两次)。
标签: java