if-then-else statement provides a secondary path of execution
when an "if" clause evaluates to false. You could use an if-then-else
statement in the applyBrakes method to take some action if the
brakes are applied when the bicycle is not in motion. In this case, the action
is to simply print an error message stating that the bicycle has already
stopped.
void applyBrakes(){
if (isMoving) {
currentSpeed--;
} else {
System.err.println("The bicycle has already stopped!");
}
}
The following program, IfElseDemo, assigns a grade based on the
value of a test score: an A for a score of 90% or above, a B for a score of 80%
or above, and so on.
class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else if (testscore >= 60) {
grade = 'D';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
The output from the program is:
You may have noticed that the value ofGrade = C
testscore can satisfy more
than one expression in the compound statement: 76 >= 70 and 76
>= 60. However, once a condition is satisfied, the appropriate
statements are executed (grade = 'C';) and the remaining conditions
are not evaluated.