Java Reference
In-Depth Information
3.6
Write an
if
statement that increases
pay
by 3% if
score
is greater than
90
, other-
wise increases
pay
by 1%.
✓
✓
Check
Point
3.7
What is the printout of the code in (a) and (b) if
number
is
30
? What if
number
is
35
?
if
(number %
2
==
0
)
System.out.println(number +
" is even."
);
if
(number %
2
==
0
)
System.out.println(number +
" is even."
);
else
System.out.println(number +
" is odd."
);
System.out.println(number +
" is odd."
);
(a)
(b)
An
if
statement can be inside another
if
statement to form a nested
if
statement.
Key
Point
The statement in an
if
or
if-else
statement can be any legal Java statement, including
another
if
or
if-else
statement. The inner
if
statement is said to be
nested
inside the outer
if
statement. The inner
if
statement can contain another
if
statement; in fact, there is no
limit to the depth of the nesting. For example, the following is a nested
if
statement:
nested
if
statement
if
(i > k) {
if
(j > k)
System.out.println(
"i and j are greater than k"
);
}
else
System.out.println(
"i is less than or equal to k"
);
The
if (j > k)
statement is nested inside the
if (i > k)
statement.
The nested
if
statement can be used to implement multiple alternatives. The statement
given in Figure 3.4a, for instance, assigns a letter grade to the variable
grade
according to the
score, with multiple alternatives.
if
(score >=
90.0
)
grade =
'A'
;
else
if
(score >=
80.0
)
grade =
'B'
;
else
if
(score >=
70.0
)
grade =
'C'
;
else
if
(score >=
60.0
)
grade =
'D'
;
else
grade =
'F'
;
if
(score >=
90.0
)
grade =
'A'
;
else if
(score >=
80.0
)
grade =
'B'
;
else if
(score >=
70.0
)
grade =
'C'
;
else if
(score >=
60.0
)
grade =
'D'
;
else
grade =
'F'
;
Equivalent
This is better
(a) (b)
A preferred format for multiple alternatives is shown in (b) using a multi-way
if-else
statement.
F
IGURE
3.4
The execution of this
if
statement proceeds as shown in Figure 3.5. The first condition
(score >= 90.0)
is tested. If it is
true
, the grade becomes
A
. If it is
false
, the second
condition
(score >= 80.0)
is tested. If the second condition is
true
, the grade becomes
B
.
If that condition is
false
, the third condition and the rest of the conditions (if necessary)
are tested until a condition is met or all of the conditions prove to be
false
. If all of the
conditions are
false
, the grade becomes
F
. Note that a condition is tested only when all of
the conditions that come before it are
false
.