Java Reference
In-Depth Information
The program generates a lottery using the
random()
method (line 6) and prompts the user
to enter a guess (line 11). Note that
guess % 10
obtains the last digit from
guess
and
guess
/ 10
obtains the first digit from
guess
, since
guess
is a two-digit number (lines 18-19).
The program checks the guess against the lottery number in this order:
1. First, check whether the guess matches the lottery exactly (line 24).
2. If not, check whether the reversal of the guess matches the lottery (lines 26-27).
3. If not, check whether one digit is in the lottery (lines 29-32).
4. If not, nothing matches and display
"Sorry, no match"
(lines 34-35).
A
switch
statement executes statements based on the value of a variable or an expression.
Key
Point
The
if
statement in Listing 3.6, 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.6:
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.6.
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.6
The
switch
statement checks all cases and executes the statements in the
matched case.