| 知乎专栏 |
package cn.netkiller.demo;
public class DemoSwitch {
public DemoSwitch() {
}
public static void main(String[] args) {
var number = 4;
var operation = "平方";
var result = switch (operation) {
case "立方" -> {
yield number * number * number;
}
case "平方" -> {
yield number * number;
}
default -> number;
};
System.out.println(result);
}
}
不必为break每个 case 块定义一个语句,我们可以简单地使用箭头语法
int money = 3;
String cn = switch (money) {
case 1 -> "壹";
case 2 -> "贰";
case 3 -> "叁";
case 4 -> "肆";
case 5 -> "伍";
case 6 -> "陆";
case 7 -> "柒";
case 8 -> "捌";
case 9 -> "玖";
case 10 -> "拾";
default -> "零";
};
System.out.println(cn);
package cn.netkiller.test;
public class Test {
public static void main(String[] args) {
withSwitchExpression(Fruit.APPLE);
withReturnValue(Fruit.AVOCADO);
withYield(Fruit.VEGETABLES);
}
private static void withSwitchExpression(Fruit fruit) {
switch (fruit) {
case APPLE, PEAR -> System.out.println("普通水果");
case MANGO, AVOCADO -> System.out.println("进口水果");
default -> System.out.println("未知水果");
}
}
private static void withReturnValue(Fruit fruit) {
System.out.println(switch (fruit) {
case APPLE, PEAR -> "普通水果";
case MANGO, AVOCADO -> "进口水果";
default -> "未知水果";
});
}
private static void withYield(Fruit fruit) {
String text = switch (fruit) {
case APPLE, PEAR, MANGO, AVOCADO -> {
System.out.println("水果: " + fruit);
yield "水果: " + fruit;
}
case VEGETABLES -> {
System.out.println("蔬菜: " + fruit);
yield "蔬菜:" + fruit;
}
default -> {
yield "未知食物";
}
};
System.out.println(text);
}
public enum Fruit {
APPLE, PEAR, MANGO, AVOCADO, VEGETABLES
}
}