use relational operators in switch

前端 未结 7 2091
终归单人心
终归单人心 2020-12-11 06:55

Is there a way to use relational operators (<,<=,>,>=) in a switch statement?

int score = 95;

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


        
7条回答
  •  -上瘾入骨i
    2020-12-11 07:38

    No you can not.
    From 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.  
    

    Relational operators (<,<=,>,>=) results in boolean and which is not allowded.

    All of the following must be true, or a compile-time error occurs:

    • Every case constant expression associated with a switch statement must be assignable (§5.2) to the type of the switch Expression.

    • No two of the case constant expressions associated with a switch statement may have the same value.

    • No switch label is null.

    • At most one default label may be associated with the same switch statement.

提交回复
热议问题