多个语句的开关规则

huangapple go评论79阅读模式
英文:

Switch Rule With Multiple Statments

问题

以下是您要求的翻译内容:

如何在多个语句中使用 switch 规则?例如,将这段代码转换为:

switch (choice) {
    case 1:
        ans = inchesToCentimeters(num);
        System.out.println(ans);
        break;
}

转换为类似于以下方式(我不确定具体如何操作,但这只是一个猜测):

switch (choice) {
    case 1 -> {
        ans = inchesToCentimeters(num);
        System.out.println(ans);
    }
}
感谢您的帮助提前致谢
英文:

How can I use switch rule with multiple statements? For ex. convert this:

switch (choice) {
            case 1:
                ans = inchesToCentimeters(num);
                System.out.println(ans);
                break;
        }

To something like this (I don't know how to do it obviously but this is just a guess):

switch (choice) {
            case 1 -> ans = inchesToCentimeters(num);
                   -> System.out.println(ans);
        }

Any help is much appreciated and thank you in advance.

答案1

得分: 5

在JDK 12中应该做如下更改:

switch (choice) {
    case 1 -> {
        ans = inchesToCentimeters(num);
        System.out.println(ans);
    }
    case 2 -> {
        // 下一个情况
    }
}

此外,你可以从switch中返回结果并修复重复的代码:

double ans = switch(choice) {
    case 1 -> inchesToCentimeters(num);
    case 2 -> centimetersToInches(num);
    case 3 -> feetToCentimeters(num);
    case 4 -> centimetersToFeet(num);
    default -> throw new IllegalArgumentException("错误的选择: " + choice);
};

System.out.println(ans);
英文:

In JDK 12 should be changed like this:

switch (choice) {
    case 1 -> {
        ans = inchesToCentimeters(num);
        System.out.println(ans);
    }
    case 2 -> {
        // next case
    }
}

Also, you could return result from switch and fix duplicated code:

double ans = switch(choice) {
    case 1 -> inchesToCentimeters(num);
    case 2 -> centimetersToInches(num);
    case 3 -> feetToCentimeters(num);
    case 4 -> centimetersToFeet(num);
    default -> throw new IllegalArgumentException("Bad choice: " + choice);
};

System.out.println(ans);

huangapple
  • 本文由 发表于 2020年10月7日 23:02:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/64246873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定