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

Java中while循环内switch每次返回相同结果的解决方法

问题根因
  • 你代码中的hi变量没有在每次循环时更新取值,Hi.nextLine()读取到的新输入没有赋值给hi,switch判断的始终是进入循环前的初始值,所以每次都会返回相同的结果。
  • 原循环条件i < 1如果没有对i的赋值逻辑,要么只能执行一次,要么会进入无意义死循环。
修复后完整代码示例
import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        // 提前定义Emotion数组示例,你可以根据自己的需求修改内容
        String[] Emotion = {"开心的", "平淡的", "沮丧的"};
        Scanner Hi = new Scanner(System.in);
        String hi = "";
        // 循环条件调整为输入exit即可退出,更合理
        while (!hi.equals("exit")) {
            // 每次循环先读取最新用户输入,赋值给hi变量
            hi = Hi.nextLine();
            switch (hi) {
                case "Hi":
                case "hi":
                case "Hi!":
                case "hi!":
                case "Hello!":
                case "hello!":
                case "Hello":
                case "hello":
                    System.out.println("Hi!");
                    break;
                case "How are you?":
                    int x = (int) (Math.random() * Emotion.length);
                    int Feeling = x;
                    System.out.println(Emotion[Feeling] + " How are you?");
                    break;
                // 补充默认分支提示,方便调试
                default:
                    if(!hi.equals("exit")) {
                        System.out.println("暂不支持该输入");
                    }
                    break;
            }
        }
        Hi.close();
    }
}
关键修改说明
  • 每次循环优先执行hi = Hi.nextLine(),将最新的用户输入赋值给switch判断的核心变量hi,保证每次判断都对应最新的输入内容
  • 调整循环退出逻辑,支持用户主动输入exit退出程序,避免原循环条件的逻辑缺陷
  • 补充了默认分支的输出提示,增加了Scanner资源关闭的逻辑,代码健壮性更强

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 05:57:03