You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改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:

  1. Explore the teams.
  2. 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:
  3. Explore the teams.
  4. Arrange a new season.
    X. Exit the system.
    Enter a choice: X
    Done

内容的提问来源于stack exchange,提问作者vishalpd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 14:02:40