java - 我怎样才能让骰子继续重新滚动和打印,直到它达到“7”或“点”
问题描述
我正在尝试构建一个掷骰子游戏,其中计算机自动掷出一对骰子,如果掷出的骰子是 7 或 11,则用户获胜。但是,如果用户掷出 2、3 或 12,他们将自动输掉。
此外,如果用户掷出任何其他数字(4、5、6、8、9、10),这是他们的“点”,他们将尝试再次掷出该点。(除非他们掷出 7 然后他们输了。)如果计算机掷出 7 或“点”以外的数字,我正试图让我的 while 循环继续滚动
不幸的是,我的循环不起作用,它不会继续重新滚动。
在此先感谢,这是我的代码:
这就是我现在所拥有的:
public class CrapsPractice{
public static void main(String[]args){
int d1 = (int) (6 * Math.random() + 1);
int d2 = (int) (6 * Math.random() + 1);
int roll = (d1 + d2);
int point = roll;
if (roll == 7 || roll == 11)
{
System.out.println("You rolled a" + roll);
System.out.println("Congrats! You've immediately won!");
return; //terminate the main function
}
else if (roll == 2 || roll == 3 || roll == 12)
{
System.out.println("you rolled a " + roll);
System.out.println("You lose!");
return; //terminate the main function
}
//do-while loop: execute and then check for condition
//and then if condition holds, execute a second time and so on
do {
int d3 = (int) (6 * Math.random() + 1);
int d4 = (int) (6 * Math.random() + 1);
roll = d3 + d4;
System.out.println("your point is" + point);
} while(roll != 7 && roll != point );
}
}
解决方案
您的代码对我有用,但请尝试使用这些打印输出来更好地了解正在发生的事情:
//do-while loop: execute and then check for condition
//and then if condition holds, execute a second time and so on
do {
int d3 = (int) (6 * Math.random() + 1);
int d4 = (int) (6 * Math.random() + 1);
roll = d3 + d4;
System.out.println("your roll is " + roll + " and point is " + point);
} while(roll != 7 && roll != point );
if (roll == 7)
System.out.println("you lose");
else
System.out.println("you win");
输出:
your roll is 6 and point is 9
your roll is 4 and point is 9
your roll is 3 and point is 9
your roll is 8 and point is 9
your roll is 8 and point is 9
your roll is 6 and point is 9
your roll is 9 and point is 9
you win
BUILD SUCCESSFUL (total time: 0 seconds)
推荐阅读
- firebase - Nuxt 中的元标记在开发环境中没有被覆盖
- android - 当屏幕关闭时,如何使用 ConnectivityManager.requestNetwork 避免“出现问题”错误?
- python - matplotlib DateFormatter 未使用 yyyy-mm-dd 列显示正确的日期
- r - 将 R markdown 直接渲染到 S3 存储桶
- macos - NSSplitView 导致 NSScrollView 绘图错误?
- python - 在 IDLE 上创建 python 代码,然后在 macOS 终端中使用它
- javascript - React 提取嵌套的 json 对象
- javascript - 在 React Native 中调用不同文件中的列表?
- reactjs - 有没有一种奇特的方法来检测取消选中复选框?
- r - 如何创建“for”循环来创建包含 R 中 NA 的列向量?