In Java is it possible to write a switch statement where each case contains more than one value? For example (though clearly the following code won't work):
switch (num) {
case 1 .. 5:
System.out.println("testing case 1 to 5");
break;
case 6 .. 10:
System.out.println("testing case 6 to 10");
break;
}
I think this can be done in Objective C, are there a similar thing in Java? Or should I just use if
, else if
statements instead?
@missingfaktor 's answer is indeed correct but a bit over-complicated. Code is more verbose (at least for continuous intervals) then it could be, and requires overloads/casts and/or parameterization for long, float, Integer etc
Here is a beautiful and minimalist way to go
It's possible to group several conditions in the same
case
statement using the mechanism of fall through allowed by switch statements, it's mentioned in the Java tutorial and fully specified in section §14.11. The switch Statement of the Java Language Specification.The following snippet of code was taken from an example in the tutorial, it calculates the number of days in each month (numbered from month 1 to month 12):
As you can see, for covering a range of values in a single
case
statement the only alternative is to list each of the possible values individually, one after the other. As an additional example, here's how to implement the pseudocode in the question:Use a
NavigableMap
implementation, likeTreeMap
.The closest you can get to that kind of behavior with
switch
statements isUse
if
statements.