use relational operators in switch

前端 未结 7 2095
终归单人心
终归单人心 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条回答
  •  不思量自难忘°
    2020-12-11 07:34

    It will never work. You should understand what switch does in the first place.

    It will execute the statements falling under the case which matches the switch argument.

    In this case, score is an argument which is 95 but score>=90 will always evaluate to either true or false and never matches an integer.

    You should use if statements instead.

    Also Java doesn't allow booleans in switch cases so yea.

提交回复
热议问题