英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论