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?
I don't think you can do that in Java. Best bet is to just put the code in the last case of the range.
You could use an
enum
to represent your ranges,Or you could use your solo cases as intended and use your default case to specify range instructions as :
Java has nothing of that sort. Why not just do the following?
No you can't do that. The best you can do is that
I know this post is old but I believe this answer deserves some recognition. There is no need to avoid the switch statement. This can be done in java but through the switch statement, not the cases. It involves using ternary operators.