Page 154 - Introduction to Programming with Java: A Problem Solving Approach
P. 154
120 Chapter 4 Control Statements
switch (<controllingexpression>) {
case <constant>: <statement(s)>; } break;
case <constant>: <statement(s)>; } break;
.. .
default: } <statement(s)>;
// end switch
optional
}
Figure 4.8 switch statement’s syntax
is reached. If there’s no break at the bottom of the last case block, control flows through to the subordi- nate statements in the default block (if there is a default block).
Referring to Figure 4.8, take note of these details:
• There must be parentheses around the controlling expression.
• The controlling expression must evaluate to either an int or a char.2 It’s illegal to use a Boolean
value, a long, a floating point value, or a string value as the controlling expression.
• Although it’s common for tAhepcoantrgolloing ePxprDesFsion tEo cnonhsisat onf acseingrle variable, it can consist of a more complicated expression as well—multiple variables, operators, and even method calls are al-
lowed—provided the expression evaluates to an int or a char.
• There must be braces around the switch statement’s body.
• There must be a colon after each case constant.
• Even though statements following the case constants are indented, braces ({ }) are unnecessary. That’s
unusual in Java—it’s the only time where you don’t need braces around statements that are logically
inside something else.
• It’s good style to include // end switch after the switch statement’s closing brace.
ZIP Code Example
To exercise your understanding of the switch statement, write a program that reads in a ZIP Code and uses the first digit to print the associated geographic area. Here’s what we’re talking about:
If ZIP Code begins with 0, 2, 3
4-6
7
8-9 other
Print this message
<zip> is on theEastCoast.
<zip> is in the CentralPlainsarea. <zip> is in the South.
<zip> is in the West.
<zip> is an invalid ZIP Code.
2 Actually, a controlling expression can also evaluate to a byte, a short, or an enum type. We discuss byte and short types in Chapter 12. Enum types are beyond the scope of this book, but if you want to learn about them on your own, see http://java.sun.com/ docs/books/tutorial/java/javaOO/enum.html.