编程语言
首页 > 编程语言> > java – 在switch中使用关系运算符

java – 在switch中使用关系运算符

作者:互联网

有没有办法在switch语句中使用关系运算符(<,< =,>,> =)?

int score = 95;

switch(score)  {
   case (score >= 90):
      // do stuff
}

上面的例子(显然)不起作用

解决方法:

你不能.
 从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.  

关系运算符(<,< =,>,> =)导致布尔值,并且不允许.

必须满足以下所有条件,否则会发生编译时错误:

>每个与switch语句关联的case常量表达式必须可分配(第5.2节)到switch表达式的类型.
>与switch语句关联的两个case常量表达式中没有两个可能具有相同的值.
>没有开关标签为空.
>最多一个默认标签可以与同一个switch语句关联.

标签:relational,java,operators,switch-statement
来源: https://codeday.me/bug/20190929/1831611.html