Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
233 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...