Java 我不明白为什么当我更改开关语句的顺序时会得到不同的输出

  • 本文关键字:顺序 输出 语句 明白 Java 开关 java
  • 更新时间 :
  • 英文 :


写入时:

System.out.println("[move,new,restart,hint,solve,quit]>");
            String input = in.next();
            switch (input){
                case "restart":
                    System.out.println("You chose restart");
                    continue;
                case "quit"://Quits out of the program
                    cont = false;
                default:
                    break;
            }
            System.out.println("here");

我得到输出:

[move,new,restart,hint,solve,quit]>
restart
You chose restart
[move,new,restart,hint,solve,quit]>
quit
here

但是,当我切换案例语句以重新启动并退出时,我会收到不同的输出:我的代码:

System.out.println("[move,new,restart,hint,solve,quit]>");
            String input = in.next();
            switch (input){
                case "quit"://Quits out of the program
                    cont = false;
                case "restart":
                    System.out.println("You chose restart");
                    continue;
                default:
                    break;
            }
            System.out.println("here");

我得到输出:

[move,new,restart,hint,solve,quit]>
restart
You chose restart
[move,new,restart,hint,solve,quit]>
quit
You chose restart

我很难理解为什么案例陈述的顺序会影响输出。

您的案例缺少"退出"逻辑的break;

switch (input){
            case "quit"://Quits out of the program
                cont = false;
                break;
            case "restart":
                System.out.println("You chose restart");
                continue;
            default:
                break;
        }
case "quit"://Quits out of the program
                    cont = false;

在这里,你没有休息或继续。因此,如果与以下所有匹配,也将执行