The switch Multiple-Selection Structure
- Occasionally, an action is selected depending on the value of an integer expression.
- A switch structure consists of a sequence of case labels, and an optional default label.
- Each case label corresponds to a particular integer value, and has some associated action.
- For example, the applet in this section tallies each kind of letter grade in a set of letter grades.
- The action method is invoked whenever enter or return is pressed.
- Its statement using the getText() method plucks the String out of the TextField, input, assigning it to the
String val.
- val.charAt(0) invokes a method, charAt(int i), whose value is the ith character in the String val.
- The 1st character in a String is at position 0.
- In this switch structure, grade is the controlling expression.
- The value of grade is compared to each of the labels (which also evaluate to integers).
- If the value matches a particular case label, the associated action[s] are taken.
- A peculiar aspect of the operation of the switch structure is that actions below the matched case label are
also executed, unless a break statement is present (at which point control exits the switch).
- Another peculiar aspect of the switch is the grammar of the action associated with a case label: It needn't be
a single statement: Braces are not needed to associate several statement with a case label.
- Similarly, several case labels can be associated with a particular action (as in the example).
- The default case is executed, when present, if no case labels are matched.
- Illustrate the flow chart of the switch structure.
- If the controlling expression is not integer-valued, you get a compiler error.