Java Reference
In-Depth Information
A
switch
statement executes statements based on the value of a variable or an
expression.
Key
Point
The
if
statement in Listing 3.5, ComputeTax.java, makes selections based on a single
true
or
false
condition. There are four cases for computing taxes, which depend on the value of
status
. To fully account for all the cases, nested
if
statements were used. Overuse of nested
if
statements makes a program difficult to read. Java provides a
switch
statement to sim-
plify coding for multiple conditions. You can write the following
switch
statement to replace
the nested
if
statement in Listing 3.5:
switch
(status) {
case
0
: compute tax for single filers;
break
;
case
1
: compute tax for married jointly or qualifying widow(er);
break
;
case
2
: compute tax for married filing separately;
break
;
case
3
: compute tax for head of household;
break
;
default
: System.out.println(
"Error: invalid status"
);
System.exit(
1
);
}
The flowchart of the preceding
switch
statement is shown in FigureĀ 3.5.
status is 0
Compute tax for single filers
break
status is 1
Compute tax for married jointly or qualifying widow(er)
break
status is 2
Compute tax for married filing separately
break
status is 3
Compute tax for head of household
break
default
Default actions
F
IGURE
3.5
The
switch
statement checks all cases and executes the statements in the
matched case.
This statement checks to see whether the status matches the value
0
,
1
,
2
, or
3
, in that
order. If matched, the corresponding tax is computed; if not matched, a message is displayed.
Here is the full syntax for the
switch
statement:
switch
statement
switch
(
switch
-expression) {
case
value1: statement(s)1;
break
;
Search WWH ::
Custom Search