Java Reference
In-Depth Information
The statements in Example 4-15 illustrate how to incorporate multiple selections using a
nested if ... else structure.
Anested if ... else structure presents an important question: How do you know
which else is paired with which if ? Recall that in Java there is no stand-alone
else statement. Every else must be paired with an if .Theruletopairan else
with an if is as follows:
Pairing an else with an if : In a nested if statement, Java associates an else with
the most recent incomplete if —that is, the most recent if that has not been paired with
an else .
Using this rule, in Example 4-15, the else in Line 3 is paired with the if in Line 1. The
else in Line 6 is paired with the if in Line 4, and the else in Line 9 is paired with the
if in Line 7.
To avoid excessive indentation, the code in Example 4-15 can be rewritten as follows:
if (balance >= 50000.00)
4
//Line 1
interestRate = 0.05;
//Line 2
else if (balance >= 25000.00)
//Line 3
interestRate = 0.04;
//Line 4
else if (balance >= 1000.00)
//Line 5
interestRate = 0.03;
//Line 6
else
//Line 7
interestRate = 0.00;
//Line 8
EXAMPLE 4-16
Assume that score is a variable of type int . Based on the value of score , the following
code determines the grade:
if (score >= 90)
System.out.println("The grade is A");
else if (score >= 80)
System.out.println("The grade is B");
else if (score >= 70)
System.out.println("The grade is C");
else if (score >= 60)
System.out.println("The grade is D");
else
System.out.println("The grade is F");
The following examples will further help you see the various ways in which you can use
nested if structures to implement multiple selection.
 
Search WWH ::




Custom Search