Why do we need break after case statements?

后端 未结 17 1969
猫巷女王i
猫巷女王i 2020-11-22 04:34

Why doesn\'t the compiler automatically put break statements after each code block in the switch? Is it for historical reasons? When would you want multiple code blocks to e

17条回答
  •  有刺的猬
    2020-11-22 04:46

    You can makes easily to separate other type of number, month, count.
    This is better then if in this case;

    public static void spanishNumbers(String span){
    
        span = span.toLowerCase().replace(" ", "");
        switch (span){
         case "1":    
         case "jan":  System.out.println("uno"); break;    
         case "2":      
         case "feb":  System.out.println("dos"); break;    
         case "3":     
         case "mar":  System.out.println("tres"); break;   
         case "4":   
         case "apr":  System.out.println("cuatro"); break;
         case "5":    
         case "may":  System.out.println("cinco"); break;
         case "6":     
         case "jun":  System.out.println("seis"); break;
         case "7":    
         case "jul":  System.out.println("seite"); break;
         case "8":    
         case "aug":  System.out.println("ocho"); break;
         case "9":   
         case "sep":  System.out.println("nueve"); break;
         case "10":    
         case "oct": System.out.println("diez"); break;
         }
     }
    

提交回复
热议问题