Using switch statement with a range of value in each case?
if-statement, java, switch-statement
Solution
after reading all the comments I didn't see anybody mention enhanced switch in which you can have multiple values in one case like this ->
switch(value){
case 1,2,3,4:
//dosth
break;
case 7,9,10,23:
//dosth
break;
}
and since in your case, there is only one expression in every case, you can do the following without the need to `break` every case->
switch (value) {
case 1, 2, 3, 4 -> System.out.println("one of 1,2,3,4 matched");
case 7, 9, 10, 23 -> System.out.println("one of 7,9,10,23 matched");
}
this is one of the many added benefits with enhanced switches in java.
Problem
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?