Java12~14 switch语法

  JDK8以后的语法没学习了,现在时代发展这么快,所以得加紧时间学习了。JDK12只有一个特性就是switch语法,算是比较容易学习的一个版本吧。总体来说就是三部分内容。具体内容可以看JEP-325的内容。

箭头语法

  每个case可以放箭头了。以下是一个例子:

public class SwitchDemo {
    public static void main(String[] args) throws IOException {
        System.out.println("请输入一个正整数:");
        int r = System.in.read();
        switch (r) {
            case '1', '2' -> System.out.println("小于3");
            case '3' -> System.out.println("等于3");
            default -> System.out.println("大于3");
        }
    }
}

switch作为表达式

  现在switch语句块可以作为表达式赋值给变量了。在以前是需要每个case块里写上赋值语句。对于这个新特性,我写了一个示例代码:

public class SwitchDemo2 {
    public static void main(String[] args) throws IOException {
        System.out.println("请输入一个正整数:");
        int r = System.in.read();
        String day = switch (r) {
            case '1' -> "Monday";
            case '2' -> "Tuesday";
            case '3' -> "Wednesday";
            case '4' -> "Thursday";
            case '5' -> "Friday";
            case '6' -> "Saturday";
            case '7' -> "Sunday";
            default -> null;
        };
        System.out.println(day);
    }
}

break/yield返回值

  在case块里,如果返回值需要复杂运算的,可以先写运算语句,再用break关键字来返回。但是这个关键字马上在新版本JDK13中被取消了。JEP-325中有这个例子:

Most switch expressions will have a single expression to the right of the “case L ->” switch label. In the event that a full block is needed, we have extended the break statement to take an argument, which becomes the value of the enclosing switch expression.
int j = switch (day) {
  case MONDAY -> 0;
  case TUESDAY -> 1;
  default -> {
    int k = day.toString().length();
    int result = f(k);
    break result;
  }
};

  但是这个代码只能在JDK12能编译通过,在JDK13中需要把break换成yield关键字。所以这样写才能编译通过:

public class SwitchDemo3 {
    public static void main(String[] args) throws IOException {
        System.out.println("请输入一个正整数:");
        int r = System.in.read();
        String s= "Foo";
        String day = switch (r) {
            case '1' -> "Monday";
            case '2' -> "Tuesday";
            case '3' -> "Wednesday";
            case '4' -> "Thursday";
            case '5' -> "Friday";
            case '6' -> "Saturday";
            case '7' -> "Sunday";
            default -> {
                System.err.println("一个星期只有7天");
                yield "不知道怎么说";
            }
        };
        System.out.println(day);
    }
}
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

醒过来摸鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值