use relational operators in switch(在 switch 中使用关系运算符)
问题描述
有没有办法在 switch 语句中使用关系运算符(<、<=、>、>=)?
Is there a way to use relational operators (<,<=,>,>=) in a switch statement?
int score = 95;
switch(score) {
case (score >= 90):
// do stuff
}
上面的例子(显然)不起作用
the above example (obviously) doesn't work
推荐答案
不,你不能.
来自 jls-14.11
The type of the Expression must be char, byte, short, int, Character, Byte, Short, Integer, String, or an enum type (§8.9), or a compile-time error occurs.
关系运算符 (<,<=,>,>=) 会产生 boolean
,这是不允许的.
Relational operators (<,<=,>,>=) results in boolean
and which is not allowded.
以下所有条件都必须为真,否则会发生编译时错误:
All of the following must be true, or a compile-time error occurs:
与 switch 语句关联的每个 case 常量表达式都必须可分配(第 5.2 节)到 switch 表达式的类型.
Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression.
与 switch 语句关联的两个 case 常量表达式不能具有相同的值.
No two of the case constant expressions associated with a switch statement may have the same value.
没有开关标签为空.
同一个switch语句最多可以关联一个默认标签.
At most one default label may be associated with the same switch statement.
这篇关于在 switch 中使用关系运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 switch 中使用关系运算符


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