Complex “if-then-else” statements are needed when there are many options e.g. consider all the options in a menu.
Fortunately, there is a better way when a lot of options are needed i.e. the “Switch-Case-Break” construct. It works exactly the same as “if-else” but its reader-friendly layout makes it easy to construct and troubleshoot. The switch statement also allows a default branch when the user types an invalid option.
If you also combine “switch” with a “while-loop” you get some robust code that can deal with erratic user input.
NOTES:
- Switch works with literal values – not variables that can possibly change during runtime.
- Switch works well with integers, String and char.
Click here for switch with integer and while.
Click here for switch with String
Click here for switch with char