Java Reference
In-Depth Information
In the previous sections, you learned how to implement one-way and two-way selections
in a program. However, some problems require the implementation of more than two
alternatives. For example, suppose that if the checking account balance is greater than or
equal to $50000, the interest rate is 5%; if the balance is greater than or equal to $25000
and less than $50000, the interest rate is 4%; if the balance is greater than or equal to
$1000 and less than $25000, the interest rate is 3%; otherwise, the interest rate is 0%. This
particular problem has four alternatives—that is, multiple selection paths. You can include
multiple selection paths in a program by using an
if
...
else
structure—if the action
statement itself is an
if
or
if
...
else
statement. When one control statement is located
within another, it is said to be nested.
EXAMPLE 4-15
Suppose that
balance
and
interestRate
are variables of type
double
. The following
statements determine the
interestRate
depending on the value of
balance
:
if
(balance >= 50000.00)
//Line 1
interestRate = 0.05;
//Line 2
else
//Line 3
if
(balance >= 25000.00)
//Line 4
interestRate = 0.04;
//Line 5
else
//Line 6
if
(balance >= 1000.00)
//Line 7
interestRate = 0.03;
//Line 8
else
//Line 9
interestRate = 0.00;
//Line 10
Suppose that the value of
balance
is
60000.00
. Then, the expression
balance >=
50000.00
in Line 1 evaluates to
true
and the statement in Line 2 executes. Now
suppose the value of
balance
is
40000.00
. Then, the expression
balance >=
50000.00
in Line 1 evaluates to
false
.Sothe
else
part at Line 3 executes. The
statement part of this
else
is an
if
...
else
statement. Therefore, the expression
balance >= 25000.00
is evaluated, which evaluates to
true
and the statement in Line
5 executes. Note that the expression in Line 4 is evaluated only when the expression in
Line 1 evaluates to
false
. The expression in Line 1 evaluates to
false
if
balance <
50000.00
and then the expression in Line 4 is evaluated. It follows that the expression
in Line 4 determines if the value of
balance
is greater than or equal to
25000
and less
than
50000
. In other words, the expression in Line 4 is equivalent to the expression
(
balance >= 25000.00 && balance < 50000.00)
. The expression in Line 7 works the
same way.
Search WWH ::
Custom Search