Java Reference
In-Depth Information
Table 4.3 if/else Options
Situation
Construct
Basic form
You want to execute any
Sequential if s
if (<test1>) {
combination of controlled
<statement1>;
statements
}
if (<test2>) {
<statement2>;
}
if (<test3>) {
<statement3>;
}
You want to execute zero
Nested if s ending in test
if (<test1>) {
or one of the controlled
<statement1>;
statements
} else if (<test2>){
<statement2>;
} else if (<test3>){
<statement3>;
}
You want to execute exactly
Nested if s ending in else
if (<test1>) {
one of the controlled
<statement1>;
statements
} else if (<test2>) {
<statement2>;
} else {
<statement3>;
}
Common Programming Error
Choosing the Wrong if/else Construct
Suppose that your instructor has told you that grades will be determined as follows:
A for scores
90
B for scores
80
C for scores
70
D for scores
60
F for scores < 60
You can translate this scale into code as follows:
String grade;
if (score >= 90) {
grade = "A";
Continued on next page
 
Search WWH ::




Custom Search