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
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
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 is95
butscore>=90
will always evaluate to eithertrue
orfalse
and never matches an integer.You should use
if
statements instead.Also Java doesn't allow
booleans
in switch cases so yea.Unfortunately NO, though you can use
case
fall (kind of hacky) by grouping multiple case statements withoutbreak
and implement code when a range ends:IMHO, using
if
would be more appropriate in your particular case.Simply NO
You are passing a
int
value toswitch
. So the case's must be inint
values, whereTurns
boolean
.Your case is a good candidaate for
if else
The docs for switch-case statement state:
So there is no boolean. Doing so would make no sence since you only have two values:
true
or false.What you could do is write a method which checks the score and then returns a one of the types
switch
can handleFor example:
and then use it in your switch:
... Or You could just use
if, else-if, else
directly!This might help you if you need to do it with switch itself,
It works this way,
No you can not.
From jls-14.11
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.