Java Reference
In-Depth Information
EXAMPLE 4-17
Assume that all variables are properly declared, and consider the following statements:
if (temperature >= 50) //Line 1
if (temperature >= 80) //Line 2
System.out.println("Good day for swimming."); //Line 3
else //Line 4
System.out.println("Good day for golfing."); //Line 5
else //Line 6
System.out.println("Good day to play tennis."); //Line 7
In this Java code, the else in Line 4 is paired with the if in Line 2, and the else in Line 6
is paired with the if in Line 1. Note that the else in Line 4 cannot be paired with the if
in Line 1. If you pair the else in Line 4 with the if in Line 1, the if in Line 2 becomes
the action statement part of the if in Line 1, leaving the else in Line 6 dangling. Also, the
statements in Lines 2 though 5 form the statement part of the if in Line 1.
EXAMPLE 4-18
Assume that all variables are properly declared, and consider the following statements:
if (temperature >= 60)
//Line 1
if (temperature >= 80)
//Line 2
System.out.println("Good day for swimming.");
//Line 3
else
//Line 4
System.out.println("Good day for golfing.");
//Line 5
In this code, the else in Line 4 is paired with the if in Line 2. Note that for the else in
Line 4, the most recent incomplete if is the if in Line 2. In this code, the if in Line 1
has no else and is a one-way selection.
Comparing if ... else Statements with a Series
of if Statements
Consider the following Java program segments, both of which accomplish the same task:
(a)
if (month == 1)
//Line 1
System.out.println("January");
//Line 2
else if (month == 2)
//Line 3
System.out.println("February");
//Line 4
else if (month == 3)
//Line 5
System.out.println("March");
//Line 6
 
 
Search WWH ::




Custom Search