-
case 穿透:
介绍:
case穿透是指在switch-case中,执行完当前case语句,因为省略了break语句,导致无法跳出switch,所以继续向下执行下一条case语句的情况。
现象:
当case穿透开始时,后续的case就会失去匹配效果,内部的语句都会被执行,直到遇到break语句跳出switch,或者将整体switch语句执行完毕,才会结束。
用途:
多个case合并
例:
import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入星期几:"); int week = sc.nextInt(); String str = ""; switch (week) { case 1: case 2: case 3: case 4: case 5: str = "工作"; break; case 6: case 7: str = "休息"; break; default: str = "输入有误"; break; } System.out.println(str); } }
-
JDK12 switch新特性:
介绍:
对switch的语法进行了扩展,这个特性可以大大简化代码,并且避免因为遗忘break语句引发bug
例(上例代码扩展):
import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("请输入星期几:"); int week = sc.nextInt(); String str = switch (week) { case 1, 2, 3, 4, 5 -> "工作"; case 6, 7 -> "休息"; default -> "输入有误"; }; System.out.println(str); } }
Java switch-case扩展 (case穿透、JDK12 switch新特性)
最新推荐文章于 2024-01-18 01:11:21 发布