if-then语句

if-then语句是所有控制流语句中最基本的。它告诉您的程序仅在特定测试的结果为true时,才执行代码的特定部分。例如,仅当自行车已经在运动中时,Bicycle类才允许制动器降低自行车的速度。applyBrakes方法的一种可能的实现方式如下:

  1. void applyBrakes() {
  2. // the "if" clause: bicycle must be moving
  3. if (isMoving){
  4. // the "then" clause: decrease current speed
  5. currentSpeed--;
  6. }
  7. }

如果该测试的评估结果为false(表示自行车没有运动),则控制跳至if-then语句的末尾。
另外,如果“then”子句仅包含一个语句,则左花括号和右花括号是可选的:

  1. void applyBrakes() {
  2. // same as above, but without braces
  3. if (isMoving)
  4. currentSpeed--;
  5. }

决定何时省略花括号是个人喜好的问题。省略它们会使代码更脆弱。如果第二条语句稍后添加到“ then”子句中,则常见的错误将是忘记添加新需要的括号。编译器无法捕获这种错误。您只会得到错误的结果。

if-then-else语句

if-then-else语句,当“if”子句的计算结果为false时,该语句提供了执行的第二路径。如果在自行车不运动时踩下制动器,则可以在applyBrakes方法中使用if-then-else语句来采取一些措施。在这种情况下,操作是简单地打印一条错误消息,指出自行车已经停止。

  1. void applyBrakes() {
  2. if (isMoving) {
  3. currentSpeed--;
  4. } else {
  5. System.err.println("The bicycle has already stopped!");
  6. }
  7. }

下面的程序 IfElseDemo根据测试分数的值来分配等级:A表示90%或更高的分数,B表示80%或更高的分数,依此类推。

  1. class IfElseDemo {
  2. public static void main(String[] args) {
  3. int testscore = 76;
  4. char grade;
  5. if (testscore >= 90) {
  6. grade = 'A';
  7. } else if (testscore >= 80) {
  8. grade = 'B';
  9. } else if (testscore >= 70) {
  10. grade = 'C';
  11. } else if (testscore >= 60) {
  12. grade = 'D';
  13. } else {
  14. grade = 'F';
  15. }
  16. System.out.println("Grade = " + grade);
  17. }
  18. }

该程序的输出为:

  1. Grade = C

您可能已经注意到,testscore复合语句中的的值可以满足多个表达式:76 >= 7076 >= 60。但是,一旦满足条件,便会执行适当的语句(grade = 'C';),并且不会评估其余条件。