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

时间:2015-12-07 01:29:51

标签: 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

但是当我切换case语句重启并退出时,我收到了不同的输出: 我的代码:

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

我很难理解为什么case语句的顺序会影响输出。

2 个答案:

答案 0 :(得分:5)

您的“退出”逻辑缺少break;

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

            default:
                break;
        }

答案 1 :(得分:2)

case "quit"://Quits out of the program
                    cont = false;

在这里你没有休息或继续。因此,如果匹配所有下面的那些也将被执行