问题描述
有没有办法在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
推荐答案
不,你不能。
来自
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.
以下所有内容必须为true,否则会发生编译时错误:
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.
这篇关于在交换机中使用关系运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!