Sam*_*ron 2 java syntax switch-statement
如何对多个语句使用 switch 规则?对于前。转换这个:
switch (choice) {
case 1:
ans = inchesToCentimeters(num);
System.out.println(ans);
break;
}
Run Code Online (Sandbox Code Playgroud)
对于这样的事情(我显然不知道该怎么做,但这只是一个猜测):
switch (choice) {
case 1 -> ans = inchesToCentimeters(num);
-> System.out.println(ans);
}
Run Code Online (Sandbox Code Playgroud)
非常感谢任何帮助,并提前感谢您。
在 JDK 12 中应该这样更改:
switch (choice) {
case 1 -> {
ans = inchesToCentimeters(num);
System.out.println(ans);
}
case 2 -> {
// next case
}
}
Run Code Online (Sandbox Code Playgroud)
此外,您可以返回结果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("Bad choice: " + choice);
};
System.out.println(ans);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4829 次 |
| 最近记录: |