增强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及之后的版本哦


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM