java - 具有 int 范围的 switch 语句
我想使用 switch 语句来检查一系列数字我发现一些地方说类似case 1...5
或 case (score >= 120) &&(score <=125)
会起作用,但我只是以某种方式不断出错.
I want to use a switch statement to check a range of numbers I have found a few places saying something like
case 1...5
or case (score >= 120) && (score <=125)
would work but I just somehow keep on getting errors.
我想要的是,如果数字在 1600-1699 之间,那就做点什么.
What I want is if the number is between 1600-1699 then do something.
我可以做 if 语句,但如果可能的话,我想是时候开始使用 switch 了.
I can do if statements but figured it's time to start using switch if possible.
推荐答案
在JVM层面上,switch
语句与if语句有着本质的区别.
On the JVM level switch
statement is fundamentally different from if statements.
Switch 是关于必须在编译时全部指定的编译时常量,以便 javac 编译器生成高效的字节码.
Switch is about compile time constants that have to be all specified at compile time, so that javac compiler produces efficient bytecode.
在 Java 中 switch
语句不支持范围. 您必须指定所有值(您可能会利用这种情况)和 default代码>案例.其他任何事情都必须由
if
语句来处理.
In Java switch
statement does not support ranges. You have to specify all the values (you might take advantage of falling through the cases) and default
case. Anything else has to be handled by if
statements.
相关文章