我是一名初学者,通过在线资源自学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
(该计划应以滚动双打结束)
答案 0 :(得分:2)
你必须再次掷骰子它们的值不相同。
在这种情况下使用do-while
很好。
int firstRoll, secondRoll;
do {
firstRoll = 1 + (int) (Math.random() * 6);
secondRoll = 1 + (int) (Math.random() * 6);
System.out.println("Roll #1: " + firstRoll);
System.out.println("Roll #2: " + secondRoll);
int total = firstRoll + secondRoll;
System.out.println("The total is " + total);
} while (firstRoll != secondRoll);
答案 1 :(得分:1)
您需要在每次迭代时再次执行滚动:
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);
firstRoll = 1 + (int) (Math.random() * 6);
secondRoll = 1 + (int) (Math.random() * 6);
}
答案 2 :(得分:1)
编写方法public int roll()
并将逻辑用于计算1-6之间的随机数。您只是输出firstRoll和secondRoll的结果,而不是在方法中再次计算它。
示例:
public class Dice() {
public int roll() {
return 1 + (int) (Math.random() * 6);
}
}
并使用它:
Dice d1 = new Dice();
Dice d2 = new Dice();
int d1Result = d1.roll();
int d1Result = d2.roll();
while (d1Result != d2Result) {
d1Result = d1.roll();
d2Result = d2.roll();
System.out.println("Result d1: " + d1Result);
System.out.println("Result d2: " + d2Result);
// Rest of logic ...
}