Java菜单方法开发遇阻:单词游戏菜单功能问题排查
单词游戏菜单问题修复与优化代码
以下是修复所有问题后的完整代码:
import java.util.Scanner; public class Small_Programming_Assignment { public static void main(String[] args) { // 仅调用菜单选择方法,游戏启动逻辑已在getSelection内处理 getSelection(); } public static void getSelection() { int selection = -1; Scanner scanner = new Scanner(System.in); // 打印菜单内容 System.out.println("Welcome 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."); while (true) { System.out.println("Enter your selection: "); if (scanner.hasNextInt()) { selection = scanner.nextInt(); // 校验输入是否在合法范围 if (selection >= 1 && selection <= 3) { break; // 输入合法,退出循环 } else { System.out.println("无效选项,请输入1、2或3"); } } else { // 处理非数字输入 System.out.println("请输入有效的数字(1、2或3)"); scanner.next(); // 消费缓冲区中的非数字内容,避免无限循环 } } // 根据选择执行对应逻辑 switch(selection) { case 1: substringProblem(); break; case 2: pointsProblem(); break; case 3: System.out.println("Goodbye"); break; } } public static void substringProblem() { System.out.println("Game 1"); } public static void pointsProblem() { System.out.println("Game 2"); } }
逐个问题的修复说明
问题1:选择合法选项后额外触发其他游戏打印
- 原因:原
main方法中,调用完getSelection()后又直接执行了substringProblem()和pointsProblem(),无论用户选什么,这两个方法都会强制运行。 - 修复:删除
main里的这两行额外调用,游戏启动逻辑已经在getSelection()的switch分支中处理完成。
问题2:输入1-3以外数字无错误提示
- 原因:原循环仅提示重新输入,未告知用户输入无效的原因。
- 修复:在判断输入数字超出1-3范围时,添加明确的错误提示语句,让用户知道问题所在。
问题3:输入非数字导致无限循环
- 原因:输入非数字时,
scanner.nextInt()会触发异常,且无效输入会留在缓冲区中,导致scanner.hasNextInt()一直返回false,循环无法终止。 - 修复:
- 先通过
scanner.hasNextInt()判断输入是否为整数; - 若为非数字输入,打印提示后用
scanner.next()清空缓冲区里的无效内容,确保后续循环能正常读取新输入。
- 先通过
内容的提问来源于stack exchange,提问作者Gauzl
相关产品推荐
相关产品推荐

