java - switch statement with range of int(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.
这篇关于java - 具有 int 范围的 switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:java - 具有 int 范围的 switch 语句


基础教程推荐
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 降序排序:Java Map 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01