Programming and Problem Solving with Java

(やまだぃちぅ) #1

(^440) | Exceptions and Additional Control Structures
As that example shows, multiple case labels may precede a single branch.
The value resulting from each Constant-Expression within a switchstatement must be
unique. If a value appears more than once among the case labels, a syntax error results. In
that scenario, the compiler simply can’t determine to which of the identical cases to branch.
Also, only one defaultlabel can appear in a switchstatement.
Be careful: case 1 does not mean the first case. We’ve listed the values in order because
it makes the statement easier to read. Java, however, allows us to place them in anyorder.
The following switchstatement behaves in exactly the same way as our earlier example:
switch(digit) // The switch expression is (digit)
{
case3 :
case2 : Statement2; // Statement2 executes if digit is 2 or 3
break; // Go to Statement5
case4 : Statement3; // Statement3 executes if digit is 4
break; // Go to Statement5
case1 : Statement1; // Statement1 executes if digit is 1
break; // Go to Statement5
default : Statement4; // Else execute Statement4 and go to
// Statement5
}
Statement5; // Always executes
The flow of control through a switchstatement goes like this: First, the switch expression
is evaluated. Next, each expression beside the reserved word caseis tested to see whether it
matches the switch expression. If the values match, control branches to the statement as-
sociated with that case label (the statement on the other side of the colon). From there, con-
trol proceeds sequentially until either a breakstatement or the end of the switchstatement
is encountered. If the value of the switchexpression doesn’t match any case value, then one
of two things happens. If there is a defaultlabel, control branches to the associated statement.
If there is no defaultlabel, the statements in the switchare skipped and control proceeds to
the statement following the entire switchstatement.
The following switchstatement prints an appropriate comment based on a student’s
grade (gradeis of type char). The switch expression can be char, as Java considers charto be
an integral type because it can be converted to type int.
switch(grade)
{
case'A' :
case'B' : outFile.print("Good Work");
break;
case'C' : outFile.print("Average Work");
break;
T
E
A
M
F
L
Y
Team-Fly®

Free download pdf