1. 程式人生 > 實用技巧 >增強switch語句的使用

增強switch語句的使用

  今天在IDEA中寫switch語句的時候,IDEA給我彈出了一個提示,是否修改為增強switch語句,

今天我們就來看看,增強版的switch語句有什麼不同

 1 package test;
 2 import java.util.Scanner;
 3 public class month_to_season {
 4     public static void main(String[] args){
 5         Scanner sc = new Scanner(System.in);//輸入月份
 6                 int month = sc.nextInt();  //下面是原版switch
7 switch(month){ 8 case 1: 9 case 2: 10 case 12: 11 System.out.println("Winter"); 12 break; 13 case 3: 14 case 4: 15 case 5: 16 System.out.println("Spring"); 17 break
; 18 case 6: 19 case 7: 20 case 8: 21 System.out.println("Summer"); 22 break; 23 case 9: 24 case 10: 25 case 11: 26 System.out.println("Autumn"); 27 break; 28 default
: 29 System.out.println("wrong!"); 30 } 31 } 32 }

這是用基礎switch語句實現輸入月份,輸出季節的程式碼

下面我將展示用增強版書寫的版本

 1 package test;
 2 import java.util.Scanner;
 3 public class month_to_season {
 4     public static void main(String[] args){
 5         Scanner sc = new Scanner(System.in);//輸入月份
 6                 int month = sc.nextInt();  //下面是增強版switch
 7         switch (month) {
 8             case 1, 2, 12 -> System.out.println("Winter");
 9             case 3, 4, 5 -> System.out.println("Spring");
10             case 6, 7, 8 -> System.out.println("Summer");
11             case 9, 10, 11 -> System.out.println("Autumn");
12             default -> System.out.println("wrong!");
13         }
14     }
15 }

可以看到,最大的特點就是看不到break了

眾所周知,break僅僅用於case穿透時才不寫,其餘時候都得加上

在增強版中,直接把要穿透的case寫到了一排,可謂是簡化了格式。

而且,整體上看,程式碼短了很多,精煉了很多,無論是交作業,還是給同學看程式碼

能給人一種更加直觀的感受。

注意:這種寫法僅適合Java12及之後的版本哦