Java 17中的switch
1. 新式switch语句的格式
switch (expression)
{
case value1 -> 表达式、代码块;
case value2, value3 -> 表达式、代码块;
// ...
default -> 表达式、代码块;
}
- case后允许同时放置多个value
- case value后的冒号变箭头
- case后的代码块不需要break
- case后代码块中定义的变量旨在该代码块内有效
2. 做为普通语句或代码块使用
var score = 'C';
switch (score)
{
case 'A', 'B' ->
{
System.out.println("成绩不错");
System.out.println("给你发奖状");
}
case 'C', 'D', 'F' -> System.out.println("成绩不足");
default -> System.out.println("成绩输入错误");
}
3. 做为表达式使用
做为表达式使用时,可以将其赋值给某个变量。
var score = 'B';
// 将switch表达式的值赋给变量
var judge = switch (score)
{
// 表达式
case 'A', 'B' -> "成绩还不错,继续保持";
case 'C', 'D', 'F' -> "成绩不足,继续努努力";
default -> "成绩输入错误";
};
System.out.println(judge);
如果表达式的case块中有多条语句,使用yield返回值。
var score = 'B';
// 将switch表达式的值赋给变量
var judge = switch (score)
{
// 表达式
case 'A', 'B' ->
{
System.out.println("成绩不错");
yield "优良";
}
case 'C', 'D', 'F' ->
{
System.out.println("成绩不足,继续努力");
yield "不足";
}
default -> "成绩输入错误";
};
System.out.println(judge);