if-then 和 if-then-else 语句

if-then 语句

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

void applyBrakes() {
    // the "if" clause: bicycle must be moving
    if (isMoving){ 
        // the "then" clause: decrease current speed
        currentSpeed--;
    }
}

如果该测试的结果为false(表示自行车没有运动),则控制跳至if-then语句的末尾。

另外,如果“ then”子句仅包含一个语句,则右括号和右括号是可选的:

void applyBrakes() {
    // same as above, but without braces 
    if (isMoving)
        currentSpeed--;
}

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

if-then-else 语句

当“ if”子句的值为false时,if-then-else语句提供了执行的辅助路径。如果在自行车不运动时踩下了制动器,则可以在applyBrakes方法中使用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 >= 7076 >= 60中的多个表达式。但是,一旦满足条件,便会执行适当的语句(grade = 'C';),并且不会评估其余条件。