Java Reference
In-Depth Information
No
Ye s
Is test1 true?
statement1
No
Ye s
Is test2 true?
statement2
No
Ye s
Is test3 true?
statement3
Figure 4.4
Flow of nested if s ending in test
When you follow this convention, the various statements all appear at the same
level of indentation. Sun recommends that nested if/else statements be indented in
this way.
Figure 4.4 shows the flow of the nested if/else code. Notice that it is possible to
execute one of the controlled statements (the first one that evaluates to true ) or none
(if no tests evaluate to true ).
In a variation of this structure, the final statement is controlled by an else instead
of a test:
if (<test1>) {
<statement1>;
} else if (<test2>) {
<statement2>;
} else {
<statement3>;
}
In this construct, the computer will always select the final branch when all the
tests fail, and thus the construct will always execute exactly one of the three state-
ments. Figure 4.5 shows the flow of this modified nested if/else code.
To explore these variations, consider the task of having the computer state whether
a number is positive, negative, or zero. You could structure this task as three simple
if statements as follows:
 
 
Search WWH ::




Custom Search