Java掷骰子模拟程序无限循环问题定位求助
Java掷骰子程序无限循环问题修复
问题根源
- 外层哨兵循环的大括号范围错误:重置计数、询问用户是否继续执行的代码,被放在了
while(runAgain == 0)的大括号外部。第一次完成10000次掷骰子后,runAgain永远保持初始值0,count也不会被重置,程序会反复输出上一次的运行结果,形成无限循环。 - 次要问题:count初始值设为-1不符合常规计数逻辑,虽不影响最终输出但可读性差,建议调整为0。
修复后的完整代码
import java.util.Random; // Needed for the Random class import java.util.Scanner; // Needed for the Scanner class /** This class simulates rolling a pair of dice 10,000 times and counts the number of times doubles of are rolled for each different pair of doubles. */ public class RollDice { public static void main(String[] args){ final int NUMBER = 10000; // Number of dice rolls // A random number generator used in // simulating the rolling of dice Random generator = new Random(); int die1Value; // Value of the first die int die2Value; // Value of the second die int snakeEyes = 0; // Number of snake eyes rolls int twos = 0; // Number of double two rolls int threes = 0; // Number of double three rolls int fours = 0; // Number of double four rolls int fives = 0; // Number of double five rolls int sixes = 0; // Number of double six rolls int runAgain = 0; // Sentinel variable Scanner keyboard = new Scanner(System.in); //Scanner Object while(runAgain == 0){ //This is a sentinel loop int count = 0; // 每次运行重置计数,放在循环内部更合理 // TASK #1 Enter your code for the algorithm here while(count < NUMBER) { // Roll both dice die1Value = generator.nextInt(6) + 1; die2Value = generator.nextInt(6) + 1; // Check to see if both dice are equal if(die1Value == die2Value) { // Check dice values and update counts if(die1Value == 1) snakeEyes++; else if(die1Value == 2) twos++; else if(die1Value == 3) threes++; else if(die1Value == 4) fours++; else if(die1Value == 5) fives++; else sixes++; } count++; } // Display the results System.out.println ("You rolled snake eyes " + snakeEyes + " out of " + count + " rolls."); System.out.println ("You rolled double twos " + twos + " out of " + count + " rolls."); System.out.println ("You rolled double threes " + threes + " out of " + count + " rolls."); System.out.println ("You rolled double fours " + fours + " out of " + count + " rolls."); System.out.println ("You rolled double fives " + fives + " out of " + count + " rolls."); System.out.println ("You rolled double sixes " + sixes + " out of " + count + " rolls."); // 重置所有计数 snakeEyes = 0; twos = 0; threes = 0; fours = 0; fives = 0; sixes = 0; // 询问用户是否重新运行 System.out.println("Do you wish to run again?"); System.out.println("Enter a 0 for yes or a -1 for no"); // 读取用户的响应 runAgain = keyboard.nextInt(); } keyboard.close(); // 用完关闭扫描器避免资源泄漏 } }
修复说明
- 把变量重置、用户询问逻辑整体移入外层
while(runAgain == 0)的大括号内部,每次完成一轮投掷后都会询问用户是否继续,更新runAgain的值,符合哨兵循环的逻辑 - 将count变量移到外层循环内部声明,每次运行自动重置,避免全局变量污染,可读性更强
- 新增Scanner的close调用,避免资源泄漏
内容的提问来源于stack exchange,提问作者Donovan Tuck
相关产品推荐
相关产品推荐

