Java Reference
In-Depth Information
Assume that
score
is an
int
variable with values between
0
and
100
.If
score
is
75
,
then
score / 10 = 75 / 10 = 7
and the grade assigned is
'C'
. If the value of
score
is
between
0
and
59
, then the grade is
'F'
.If
score
is between
0
and
59
,
score / 10
is
0
,
1
,
2
,
3
,
4
,or
5
; each of these values corresponds to the grade
'F'
.
Therefore, in this
switch
structure, the action statements of
case
0
,
case
1
,
case
2
,
case
3
,
case
4
,and
case
5
are all the same. Rather than write the statement
grade = 'F';
followed by the
break
statement for each of the
case
values of
0
,
1
,
2
,
3
,
4
,and
5
, you can
simplify the programming code by first specifying all of the case values (as shown in the
preceding code) and then specifying the desired action statement. The
case
values of
9
and
10
follow similar conventions.
4
CHOOSING BETWEEN AN
if
...
else
AND A
switch
STRUCTURE
As you can see from the preceding examples, the
switch
statement is an elegant way to
implement multiple selections. You will see a
switch
statement used in the program-
ming examples in this chapter. There are no fixed rules that can be applied to decide
whether to use an
if
...
else
structure or a
switch
structure to implement multiple
selections, but you should remember the following consideration: If multiple selections
involve a range of values, you should use either an
if
...
else
structure or a
switch
structure wherein you convert each range to a finite set of values.
For instance, in Example 4-22, the value of
grade
depends on the value of
score
.If
score
is
between
0
and
59
,
grade
is
'F'
.Because
score
is an
int
variable, 60 values correspond to
the grade of
'F'
.Ifyoulistall60valuesas
case
values, the
switch
statement could be very
long. However, dividing by 10 reduces these 60 values to only 6 values:
0
,
1
,
2
,
3
,
4
,and
5
.
If the range of values is infinite and you cannot reduce them to a set containing a finite
number of values, you must use the
if
...
else
structure. For example, suppose that
score
is a
double
variable. The number of
double
values between
0
and
60
is
(practically) infinite. However, you can use the expression (
int)
(score) / 10
and
reduce the infinite number of values to just six values.
Concepts and Techniques (Revisited)
Earlier in this chapter, we discussed how a partial understanding of a concept or technique
can lead to errors in a program. In this section, we give another example to illustrate
the problem of using partially understood concepts and techniques. In Example 4-22, we
illustrated how to assign a grade based on a test score between 0 and 100. Next consider the
following program that assigns a grade based on a test score.
DEBUGGING
Search WWH ::
Custom Search