Java中switch的多种写法
代码需求:键盘录入一个数字(代表星期几),判断是工作日还是休息日
switch最基础写法
public static void switchTest() {
while (true) {
System.out.println("请输入:");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
switch (num) {
case 1:
System.out.println("工作日");
break;
case 2:
System.out.println("工作日");
break;
case 3:
System.out.println("工作日");
break;
case 4:
System.out.println("工作日");
break;
case 5:
System.out.println("工作日");
break;
case 6:
System.out.println("休息日");
break;
case 7:
System.out.println("休息日");
break;
default:
System.out.println("输入错误");
break;
}
System.out.println();
}
}
switch穿透现象
public static void switchTest1() {
while (true) {
System.out.println("请输入:");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
switch (num) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("工作日");
break;
case 6:
case 7:
System.out.println("休息日");
break;
default:
System.out.println("输入错误");
break;
}
System.out.println();
}
}
JDK14之后switch新特性1
public static void switchTest2() {
while (true) {
System.out.println("请输入:");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
switch (num) {
case 1, 2, 3, 4, 5:
System.out.println("工作日");
break;
case 6, 7:
System.out.println("休息日");
break;
default:
System.out.println("输入错误");
break;
}
System.out.println();
}
}
JDK14之后switch新特性2
public static void switchTest3() {
while (true) {
System.out.println("请输入:");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
switch (num) {
case 1, 2, 3, 4, 5 -> System.out.println("工作日");
case 6, 7 -> System.out.println("休息日");
default -> System.out.println("输入错误");
}
System.out.println();
}
}