Consider a simple user menu for a store simulation program. There should be options to buy certain items, check your total money spent, cancel items selected, exit, and finish and pay. We could take the input from this menu and do a complicated, nested series of if-else
statements, but that would quickly become bulky and difficult to read. However, there is an easy way to handle such data input with a switch
statement. Depending on which command is chosen, the program will select one direction out of many. The AP exam does not test on the switch
statement, but we include it here at the end of this chapter because it is a very useful tool to have in your programming toolkit.
The general form of a switch
statement is:
The flow of control of a switch
statement is illustrated in this diagram:
The switch
statement attempts to match the integer value of the expression with one of the case
values.
If a match occurs, then all statements past the case
value are executed until a break
statement is encountered.
The effect of the break statement causes program control to jump to the end of the switch statement. No other cases are executed.
A very common error when coding a switch
control structure is forgetting to include the break
statements to terminate each case value. If the break
statement is omitted, all the statements following the matching case
value are executed. This is usually very undesirable.
If it is possible that none of the case statements will be true, you can add a default
statement at the end of the switch
. This will only execute if none of the case statements happened. If all possibilities are covered in your case statements, the default
statement is unnecessary. Note that the default
statement can actually be placed anywhere. If you place the default
in the beginning or middle of the switch
, you will probably want to end the default
case with a break
. Otherwise, execution will continue with the case after the default
.
The following example applies the switch statement to printing the work day of the week corresponding to a value. We pass in the integer day:
Suppose we wanted to count the occurrences of vowels and consonants in a stream of text.
There are programming situations where the switch
statement should not replace an if-else
chain. If the value being compared must fit in a range of values, the if-else
statement should be used.
etc...
You should not replace the above structure with a switch statement.
Finally, the switch
statement cannot compare double
values.
For more information, you can read the documentation from Oracle.
Last modified: October 01, 2024
Back to Boolean Identifiers