2015-12-07 42 views
1

的顺序当我写:Java的,我不明白为什么我得到不同的输出,当我改变我的switch语句

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"); 

我得到的OU输入:

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

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

+1

时间使用调试器。 –

+0

听说过break语句? –

回答

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; 
     } 
2
case "quit"://Quits out of the program 
        cont = false; 

这里您没有休息或继续。因此,如果符合以下所有的人也将得到执行

相关问题