本文详解如何通过正确声明循环变量和优化 do-while 结构,使基于 switch-case 的控制台菜单在完成任意功能后持续运行并重
新显示,避免程序意外退出或抛出 nosuchelementexception。
在 Java 控制台程序中实现“功能执行后自动返回主菜单”,关键在于循环作用域与输入读取的协同设计。你遇到的问题(NoSuchElementException、程序提前终止)根本原因有两个:
✅ 正确做法是:将 selection 提升为循环外声明的局部变量,并确保每次循环都重新获取有效输入。以下是修复后的完整结构:
public static void main(String[] args) {
String menu = "Please choose one option from the following menu: \n" +
"1. Calculate the sum of integers 1 to m\n" +
"2. Calculate the factorial of a given number\n" +
"3. Calculate the amount of odd integers in a given sequence\n" +
"4. Display the leftmost digit of a given number\n" +
"5. Calculate the greatest common divisor of two given integers\n" +
"6. Quit\n";
Scanner console = new Scanner(System.in);
int selection = 0; // ✅ 在循环外声明,作用域覆盖整个 do-while
do {
System.out.print(menu); // 使用 print 避免多余空行
selection = console.nextInt(); // ✅ 每次循环均重新读取
switch (selection) {
case 1:
sumOfIntegers();
break;
case 2:
factorialOfNumber();
break;
case 3:
calcOddIntegers();
break;
case 4:
displayLeftDigit();
break;
case 5:
greatestCommonDivisor();
break;
case 6:
System.out.println("Bye");
break;
default:
System.out.println("Invalid choice. Please enter 1–6.");
break; // ✅ 增加默认分支提升健壮性
}
// ✅ 可选:在每次功能执行后添加暂停提示(如按回车继续)
// System.out.print("Press Enter to continue...");
// console.nextLine(); // 清除残留换行符(尤其当其他方法含 nextLine() 时)
} while (selection != 6);
console.close();
}⚠️ 重要注意事项:
? 进阶建议:为提升用户体验,可在每个 case 执行完毕后添加 System.out.println("\n--- Returning to menu ---\n");,明确反馈流程状态。这样,菜单不仅“能返回”,而且“可感知、易维护、抗误操作”。