gpt4 book ai didi

java - Java 中的 Switch case 逻辑表达式语句——对比 JS 或 PHP

转载 作者:行者123 更新时间:2023-11-29 03:33:54 25 4
gpt4 key购买 nike

在 JavaScript 中,我也在 PHP 中看到过:您可以在案例中使用逻辑表达式:例如:

switch(true){
case (d<10):
document.write("Less than 10");
break;
case (d==10):
document.write("Equal to 10");
break;
case (d>10):
document.write("Greater than 10");
break;
default:
document.write("Some dumb error. Probably not a number.");
}

我想知道我们是否可以在 Java 中做到这一点……假设我需要一个来比较一个非常大的范围。

case 1 :
case 2 :
...
case 5000:
case 5001:
default:

这样做会很乏味。我可以将我的案例包装在 if 语句中,但我想知道它可以像在 JavaScript 或 PHP 中那样完成。

最佳答案

很高兴拥有,但你不能。引用 JLS:

The body of a switch statement is known as a switch block.

Any statement immediately contained by the switch block may be labeled with one or more switch labels, which are case or default labels.

These labels are said to be associated with the switch statement, as are the values of the constant expressions (§15.28) or enum constants (§8.9.1) in the case labels.

这些标签必须是常量表达式或枚举常量

关于java - Java 中的 Switch case 逻辑表达式语句——对比 JS 或 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16534025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com