If-then-else语句在“ if”子句的计算结果为 false 时提供辅助执行路径。如果在自行车不运行时应用了刹车,那么可以在 applicyBrakes ()方法中使用 if-then-else 语句来执行某些操作。在这种情况下,操作是简单地打印一个错误消息,说明自行车已经停止。
void applyBrakes() { if (isMoving) { currentSpeed--; } else { System.err.println("The bicycle has already stopped!"); } }
下面的程序 IfElseDemo 根据测试分数的值给分: A 代表90% 或以上的分数,B 代表80% 或以上的分数,依此类推。
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); } }
该方案的输出是:
Grade = C
您可能已经注意到 testscore 的值可以满足复合语句中的多个表达式: 76 > = 70和76 > = 60。但是,一旦条件得到满足,就执行适当的语句(grade = ‘ C’;) ,并且不计算其余的条件。