switch表达式
约 131 字小于 1 分钟
2025-07-22
提示
需要 Java14+
才能使用
类似 PHP
中的 match
语法
class Main {
public static void main(String[] args) {
int score = 100;
switch (score) {
case 100 -> System.out.println("Perfect score!");
case 90, 95 -> System.out.println("Great job!");
case 80 -> System.out.println("Good effort!");
case 70 -> System.out.println("You passed.");
default -> System.out.println("Keep trying!");
}
switch (score) {
// 声明一个代码块也是可以的
case 100 -> {
System.out.println("Perfect score!");
// 返回的内容使用 yield 关键字
yield "A";
}
default -> System.out.println("Keep trying!");
}
char grade = switch (score) {
case 100 -> 'A';
case 90, 95 -> 'B';
case 80 -> 'C';
case 70 -> 'D';
default -> 'F';
};
}
}