Java do-while循环异常:输入'n'偶不终止、积分耗尽未停止
问题修复方案
核心错误分析
- 循环终止逻辑完全写反:外层
do-while的条件repeat.equals("n") || points != 0逻辑完全颠倒——它表示「用户输入'n' 或者 积分不等于0时继续循环」,和你期望的「输入'n'终止、积分<=0终止」完全相反。 - 积分耗尽无法终止:原条件里
points !=0会导致积分变成负数时,循环依然满足条件继续执行,因为负数不等于0。
额外优化点
- 内层赌金额度校验只判断了
gambleAmount > points,没处理用户输入负数的情况 - 规则说明里的
Numbers 8-13未标注是high,逻辑不完整 - 随机数为7时,用户猜0或1都会输,但没有明确提示原因
修复后的完整代码
package highlow; import java.util.Scanner; public class Highlow { public static void Rules() { System.out.println("RULES:"); System.out.println("Numbers 1-6 are low "); System.out.println("Numbers 8-13 are high"); // 补全规则说明 System.out.println("Number 7 is neither high or low\n"); } public static void main(String[] args) { int number; int gambleAmount; int prediction; int correctRange; int winnings; int points; int numberOfGuesses = 0; String repeat; Scanner input = new Scanner(System.in); points = 1000; System.out.print("High Low Game\n\n"); Rules(); do { number = (int) (13 * Math.random() + 1); if (number > 7) { correctRange = 1; } else if (number < 7) { correctRange = 0; } else { correctRange = -1; } numberOfGuesses += 1; System.out.println("You have " + points + " points"); // 修复赌金额度校验:增加负数/0判断 do { System.out.println("Please insert a valid number of points"); System.out.print("How many points would you like to gamble: "); gambleAmount = input.nextInt(); } while (gambleAmount > points || gambleAmount <= 0); System.out.print("Predict [1=high, 0=low]: "); prediction = input.nextInt(); if (prediction == correctRange) { winnings = gambleAmount * 2; points = points + winnings; System.out.println("The number was " + number); System.out.print("You win!\n\n"); } else { points = points - gambleAmount; System.out.println("The number was " + number); // 增加7的输局提示 if (correctRange == -1) { System.out.println("Result is neutral (7), so you lose!\n"); } else { System.out.print("You lose\n\n"); } } // 积分耗尽直接结束,无需询问 if (points <= 0) { System.out.println("You have no points left, game over!"); break; } System.out.print("Would you like to play again ('n' for no and 'y' for yes): "); repeat = input.next(); // 修复循环条件:仅当用户输入'y'(不区分大小写)且积分>0时继续 } while (repeat.equalsIgnoreCase("y") && points > 0); System.out.print("You had " + numberOfGuesses + " guesses"); input.close(); // 关闭Scanner避免资源泄漏 } }
关键修复说明
- 外层循环条件改为
repeat.equalsIgnoreCase("y") && points > 0:严格控制只有用户想继续且还有积分时,才执行下一轮游戏 - 内层赌金额度校验增加
gambleAmount <=0判断:防止用户输入无效的负数或0 - 增加积分<=0时的主动跳出逻辑:用户没钱后直接结束游戏,无需多余询问
- 补全规则说明和7的输局提示:提升游戏体验
- 关闭Scanner:避免资源泄漏
内容的提问来源于stack exchange,提问作者Tristan Day
相关产品推荐
相关产品推荐

