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?
Java has nothing of that sort. Why not just do the following?
public static boolean isBetween(int x, int lower, int upper) {
return lower <= x && x <= upper;
}
if (isBetween(num, 1, 5)) {
System.out.println("testing case 1 to 5");
} else if (isBetween(num, 6, 10)) {
System.out.println("testing case 6 to 10");
}