java - Java:掷骰子游戏:退出循环然后重新进入
问题描述
这是一个模拟骰子游戏Craps的程序。规则是,如果你掷出 7 或 11,你就赢了。如果您掷出 2、3 或 12,则您输了。如果您滚动其他任何东西,您将获得“点”并被允许再次滚动。如果你分配 2 分,你也赢了。
我在这里遇到的麻烦是积分系统。我不知道如何存储该点,然后退出循环并提示用户再次滚动以重新进入循环。
import javax.swing.JOptionPane;
public class DiceGame {
public static void main(String args[ ]) {
// declarations
int dieNumber1,
dieNumber2,
point,
score;
// initializations
dieNumber1 = (int)(Math.random( ) * 6 + 1);
dieNumber2 = (int)(Math.random( ) * 6 + 1);
score = dieNumber1 + dieNumber2;
// executable statements
for (int i = 0; i < 10000; i++)
{
System.out.println ("Roll the die");
System.out.println ("You rolled a " + score);
if (score == 11 || score == 7)
{
System.out.println ("You Win!");
break;
}
if (score == 2 || score == 3 || score == 12)
{
System.out.println ("You Lose.");
break;
}
if (score == 4 || score == 5 || score == 6 || score == 8 || score == 9 || score == 10)
{
point = 1;
System.out.println ("You got a point.");
}
}
System.exit(0);
} // end of the main method
} // end of the class
解决方案
您可能需要明确考虑程序的流程应该如何运行。即:每卷有三种结果:赢、输、分。我们什么时候想循环?我假设(你的答案可能不同)当我们想再次滚动时。我们什么时候想再次滚动?我假设(你的答案可能不同)当用户得到一个点时。因此,重点案例应该是我们循环的结果,任何其他结果都应该导致不循环。
请注意,因为我们总是需要在进行任何其他逻辑之前进行滚动(如果我们不滚动,则无法决定赢/输/分),我们将滚动逻辑放在循环中:
那么我们的代码会是什么样子呢?
import javax.swing.JOptionPane;
public class DiceGame {
public static void main(String args[ ]) {
// Initialize some things (omitted)
while(true) { // NOTE: it's generally good form to use while(true) for a loop that could continue forever, instead of a for-loop with a very high number
// Roll the dice (omitted)
if (score == 11 || score == 7)
{
System.out.println ("You Win!");
break; // Game over. Get out of our infinite loop.
}
if (score == 2 || score == 3 || score == 12)
{
System.out.println ("You Lose.");
break; // As above
}
else // If our score is anything else we must have gotten a point
{
point = 1; // Don't break. We want to roll again
}
}
}
}
推荐阅读
- javascript - 在我的 Nodejs 项目中编辑产品时出现问题
- c - 如何在c中的同一行上打印两个字符串
- angular - CI 无法构建 Angular 8 应用程序
- sql - 如何在不使用 varchar 数据的情况下在 Presto SQL 中进行重复数据删除
- wordpress - 为页面分配类别并将其显示在 URL slug 中
- google-apps-script - 在 Google Apps 脚本中,“AdminDirectory.Groups.insert(group)”命令是否被视为发布请求?
- batch-file - 使用 (copy #) 删除本地打印机
- android - 由于 Androidx 和 Android 支持最新版本之间的冲突导致构建错误
- c# - 如何在任务管理器中使用不同的进程名称(对于当前进程)名称?
- .net-core - 在两个实体与另一个上下文中的第三个实体之间创建映射的最佳方法