I have multiple cases in a switch that do the same thing, like so: (this is written in Java)
case 1:
aMethod();
break;
case 2:
aMethod();
break;
case 3:
aMethod();
break;
case 4:
anotherMethod();
break;
Is there any way I can combine cases 1, 2 and 3 into one case, since they all call the same method?
A switch statement includes multiple cases that include code blocks to execute. A break keyword is used to stop the execution of case block. A switch case can be combined to execute same code block for multiple cases.
Therefore nested switch statements should be avoided. Specifically, you should structure your code to avoid the need for nested switch statements, but if you cannot, then consider moving the inner switch to another function.
If no cases are matched and default is not provided, just nothing will be executed. Save this answer.
In practice, fallthrough is usually prevented with a break keyword at the end of the matching body, which exits execution of the switch block, but this can cause bugs due to unintentional fallthrough if the programmer forgets to insert the break statement.
case 1:
case 2:
case 3:
aMethod();
break;
case 4:
anotherMethod();
break;
This works because when it happens to be case 1 (for instance), it falls through to case 2 (no break
statement), which then falls through to case 3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With