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
Obviously, this is not possible as a language construct. But, just for fun, we could implement it by ourselves!
Switch
accepts any value to switch on and then provides functionality to match over boolean conditions (ifTrue
method) or by exact matches (ifEquals
method). Providing a value to switch on is needed just for the latter feature.After building the conditions, user invokes
getResult
to obtain the result.For example, we could create a method that tells us what it thinks about our score:
This simple test:
Prints out: