如何在Java猜数字游戏中实现‘end game’终止功能并避免输入崩溃
解决猜数字游戏中输入"end game"崩溃的问题
嘿,我完全懂你遇到的头疼问题——用nextInt()读取输入时,只要用户敲入"end game"这类字符串,程序直接就因类型不匹配崩了。这是因为nextInt()只认整数,碰到非数字输入就会触发异常,咱们一步步来搞定它:
问题根源
Scanner.nextInt()会强制把输入内容解析成整数,如果输入的是像"end game"这样的字符串,它就会抛出InputMismatchException,而且错误的输入还会留在Scanner的缓冲区里,后续读取操作也会跟着出问题。
解决方案思路
我们需要先捕获用户的全部输入内容,再判断是数字还是结束指令:
- 用
Scanner.nextLine()代替nextInt(),这样不管用户输入数字还是字符串都能完整获取。 - 尝试把读取到的字符串转换成整数:
- 转换成功:就用这个数字作为猜测值继续游戏。
- 转换失败:检查是不是"end game",是的话跳回主菜单;不是的话提示用户输入有效内容。
- 处理输入缓冲区的换行残留:比如用
next()之后,缓冲区会留下换行符,得用nextLine()消耗掉,避免后续读取空内容。
修改后的完整代码(重点优化number方法)
import java.util.Scanner; public class TwoGames { public static void main(String[] args) { // 主菜单 Scanner scan = new Scanner(System.in); System.out.println("Choose the game\nType 'letter' or 'number' to choose the game"); String userAnswer = scan.next(); scan.nextLine(); // 消耗next()后的换行符,避免影响后续nextLine() if (userAnswer.equalsIgnoreCase("number")) { number(args); } else if(userAnswer.equalsIgnoreCase("letter")){ letter(args); } scan.close(); } public static void letter (String[] args) { Scanner scan = new Scanner(System.in); String playAgain = ""; String returnToMenu = ""; int numberOfTries = 0; do { System.out.println("Guess the Letter"); char randomLetter = (char) (Math.random() * 26 + 65); char enteredLetter = 0; while(true){ String input = scan.nextLine().trim(); if(input.isEmpty()){ System.out.println("Please enter a valid letter!"); continue; } enteredLetter = Character.toUpperCase(input.charAt(0)); numberOfTries++; if(enteredLetter == randomLetter) { System.out.println("Correct Guess"); System.out.println("The letter is:" + randomLetter); System.out.println("It only took you " + numberOfTries + " tries! Good work!"); break; } else if(enteredLetter > randomLetter) { System.out.println("Incorrect Guess"); System.out.println("The letter entered is too high"); } else if(enteredLetter < randomLetter) { System.out.println("Incorrect Guess"); System.out.println("The letter entered is too low"); } } System.out.println("Would you like to play again (y/n)?"); playAgain = scan.next(); scan.nextLine(); // 消耗换行符 } while (playAgain.equalsIgnoreCase("y")); System.out.println("Thank you for playing! Goodbye!\nType 'return' to return to main menu"); returnToMenu = scan.next(); if (returnToMenu.equalsIgnoreCase("return")) main(args); scan.close(); } public static void number(String[] args) { Scanner scan = new Scanner(System.in); String playAgain = ""; String returnToMenu = ""; do { int theNumber = (int)(Math.random() * 100 + 1); int numberOfTries = 0; boolean isGameRunning = true; while (isGameRunning) { System.out.println("Guess a number between 1 and 100 (or type 'end game' to quit to main menu):"); String input = scan.nextLine().trim(); // 检查是否是结束游戏指令 if(input.equalsIgnoreCase("end game")){ isGameRunning = false; main(args); // 跳回主菜单 continue; } // 尝试转换输入为整数 Integer guess = null; try{ guess = Integer.parseInt(input); } catch(NumberFormatException e){ System.out.println("Invalid input! Please enter a number or 'end game' to quit."); continue; } // 验证数字范围 if(guess < 1 || guess > 100){ System.out.println("Please enter a number between 1 and 100!"); continue; } numberOfTries++; if (guess < theNumber) { System.out.println(guess + " is too low. Try again."); } else if (guess > theNumber) { System.out.println(guess + " is too high. Try again."); } else { System.out.println(guess + " is correct. You win!"); System.out.println("It only took you " + numberOfTries + " tries! Good work!"); isGameRunning = false; // 猜对后结束当前游戏轮次 } } System.out.println("Would you like to play again (y/n)?"); playAgain = scan.next(); scan.nextLine(); // 消耗换行符 } while (playAgain.equalsIgnoreCase("y")); System.out.println("Thank you for playing! Goodbye!\nType 'return' to return to main menu"); returnToMenu = scan.next(); if (returnToMenu.equalsIgnoreCase("return")) main(args); scan.close(); } }
关键改动说明
- 替换输入读取方式:用
nextLine()捕获全部输入,避免类型不匹配异常。 - 整数转换与异常处理:用
Integer.parseInt()尝试转换输入,失败时捕获NumberFormatException,给用户友好提示。 - 提前判断结束指令:在转换整数前先检查输入是不是"end game",满足条件直接跳回主菜单。
- 处理换行残留:每次用
next()读取后,调用scan.nextLine()清空缓冲区的换行符,避免后续nextLine()读到空内容。 - 优化游戏逻辑:用
isGameRunning布尔变量控制游戏循环,比嵌套do-while更清晰易懂。
这样修改后,用户输入"end game"就能正常跳回主菜单,输入无效内容也不会崩溃,游戏体验顺畅多啦~
内容的提问来源于stack exchange,提问作者Henzi




