Java小游戏整数输入错误处理失效,非整数输入致程序崩溃求助
问题分析与解决方案
问题原因
- 非整数输入直接触发异常:代码中先执行
int choice = sc.nextInt();,如果用户输入非整数,nextInt()会立即抛出InputMismatchException,程序直接崩溃,根本无法进入后续的错误判断逻辑。 - 重复创建Scanner实例:每次调用
getSelection()都新建Scanner,会导致输入流资源泄漏,还可能引发读取异常。 - main方法逻辑冗余:
main中调用getSelection()后又执行substringProblem()和pointsProblem(),但这两个方法内部已经会调用getSelection(),导致程序流程混乱。
修正后的代码
import java.util.Scanner; public class Small_Programming_Assignment { public static void main(String[] args) { Scanner sc = new Scanner(System.in); getSelection(sc); } public static void getSelection(Scanner sc) { System.out.println("\nWelcome to the Word Games program menu."); System.out.println("Select from one of the following options."); System.out.println("1. Substring problem."); System.out.println("2. Points problem."); System.out.println("3. Exit."); System.out.println("Enter your selection: "); int choice = -1; // 先判断输入是否为整数 if (sc.hasNextInt()) { choice = sc.nextInt(); // 判断整数是否在合法范围 if (choice >= 1 && choice <= 3) { switch (choice) { case 1: substringProblem(sc); break; case 2: pointsProblem(sc); break; case 3: System.out.println("Goodbye!"); System.exit(0); } } else { System.out.println("Invalid option. Try again."); getSelection(sc); } } else { // 清除缓冲区中的无效非整数内容 sc.next(); System.out.println("Invalid option. Try again."); getSelection(sc); } } public static void substringProblem(Scanner sc) { System.out.println("Substring Problem"); getSelection(sc); } public static void pointsProblem(Scanner sc) { System.out.println("Points Problem"); getSelection(sc); } }
关键修改说明
- 复用Scanner实例:在
main中创建唯一的Scanner,通过参数传递给各个方法,避免重复创建引发的资源问题。 - 前置输入校验:先调用
sc.hasNextInt()确认输入为整数后,再执行nextInt()读取,从根源避免输入非整数时的异常崩溃。 - 清除无效输入:遇到非整数输入时,用
sc.next()清空缓冲区的无效内容,防止下一次读取时重复获取到相同的无效输入,避免死循环。 - 简化分支逻辑:用
switch替代多分支if-else,同时先校验整数范围,让逻辑更清晰。 - 移除冗余调用:删除
main中多余的substringProblem()和pointsProblem()调用,让程序流程完全由getSelection()控制。
内容的提问来源于stack exchange,提问作者Gauzl
相关产品推荐
相关产品推荐

