在 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.
相关文章