如何修改Java的while循环,在非X输入时打印提示并重新执行方法?
修改后的代码实现
先看调整后的完整代码:
public void associationMenu() { char choice; do { choice = Character.toUpperCase(readChoice()); // 统一转大写,兼容小写x输入 if (choice != 'X') { switch (choice) { case '1': exploreTeams(); break; case '2': newSeason(); break; default: // 非法输入时打印要求的提示语句 System.out.println("Please enter a number 1 or 2, or press X to exit."); } } } while (choice != 'X'); // 输入X时退出循环 System.out.println("Done"); } public char readChoice() { associationMenuHelp(); // 打印菜单头部信息 System.out.print("Enter a choice: "); return In.nextChar(); }
关键修改说明
- 把递归调用换成
do-while循环:原代码用递归处理非法输入,多次错误操作会触发栈溢出,循环实现更安全稳定 - 统一字符大小写:通过
Character.toUpperCase()将输入转为大写,兼容用户输入小写x的场景 - 增加非法输入提示:当输入不是
1、2、X时,直接打印要求的提示语句,之后进入下一轮循环重新读取选择 - 调整循环逻辑:
do-while保证菜单至少被加载一次,符合正常交互流程
对应示例运行效果
Welcome to the Association! Please make a selection from the menu:
- Explore the teams.
- Arrange a new season.
X. Exit the system.
Enter a choice: x
Please enter a number 1 or 2, or press X to exit.
Welcome to the Association! Please make a selection from the menu:- Explore the teams.
- Arrange a new season.
X. Exit the system.
Enter a choice: X
Done
内容的提问来源于stack exchange,提问作者vishalpd
相关产品推荐
相关产品推荐

