Java switch语法的踩坑

在工作中用switch出了bug,所以发现原本我对switch的理解是不对的,我一开始以为swith是严格按照case里的选项来执行的,后来发现不是的:

 1         String s = "come";
 2         switch (s){
 3             case "come":
 4                 if (1 == 2){
 5                     System.out.println("come output 1");
 6                 }else if (3 == 4){
 7                     System.out.println("come output 2");
 8                 }
 9             case "go":
10                 System.out.println("go output");
11         }

结果输出的是"go output",也就是不只按case "come"里的执行

所以写switch一定要写个兜底语句来保险,不然容易出错。如这样兜底:

 1         String s = "come";
 2         switch (s){
 3             case "come":
 4                 if (1 == 2){
 5                     System.out.println("come output 1");
 6                 }else if (3 == 4){
 7                     System.out.println("come output 2");
 8                 }
 9                 System.out.println("come output 3");
10             case "go":
11                 System.out.println("go output");
12         }

Written on Dec. 20th, 2019

原文地址:https://www.cnblogs.com/LittleMike/p/12074128.html