Just trying to figure out how to use many multiple cases for a Java switch statement. Here\'s an example of what I\'m trying to do:
switch (variable)
{
c
According to this question, it's totally possible.
Just put all cases that contain the same logic together, and don't put break behind them.
switch (var) {
case (value1):
case (value2):
case (value3):
//the same logic that applies to value1, value2 and value3
break;
case (value4):
//another logic
break;
}
It's because case without break will jump to another case until break or return.
EDIT:
Replying the comment, if we really have 95 values with the same logic, but a way smaller number of cases with different logic, we can do:
switch (var) {
case (96):
case (97):
case (98):
case (99):
case (100):
//your logic, opposite to what you put in default.
break;
default:
//your logic for 1 to 95. we enter default if nothing above is met.
break;
}
If you need finer control, if-else is the choice.