if

if-else 语句 属于 Java

40 个练习

关于 if-else 语句

if-then 语句

Java 中最基本的控制流语句是 if-then 语句。 这条语句只在某个条件为true时执行某段代码。 if-then 语句通过if子句定义:

class Car {
    void drive() {
        // the "if" clause: the car needs to have fuel left to drive
        if (fuel > 0) {
            // the "then" clause: the car drives, consuming fuel
            fuel--;
        }
    }
}

在上面的例子中,如果汽车没油了,调用Car.drive方法不会有任何效果。

if-then-else 语句

当if子句中的条件求值为false时,if-then-else 语句会提供一条替代的执行路径。 这条替代执行路径紧跟在if子句之后,通过else子句定义:

class Car {
    void drive() {
        if (fuel > 0) {
            fuel--;
        } else {
            stop();
        }
    }
}

在上面的例子中,如果汽车没油了,调用Car.drive方法会调用另一个方法来让汽车停下。

if-then-else 语句还可以通过else if子句支持多个条件:

class Car {
    void drive() {
        if (fuel > 5) {
            fuel--;
        } else if (fuel > 0) {
            turnOnFuelLight();
            fuel--;
        } else {
            stop();
        }
    }
}

在上面的例子中,当油量小于或等于5时驾驶汽车,汽车仍会前进,但会亮起油量指示灯。 当油量降到0时,汽车就会停下来。

通过 GitHub 编辑 该链接会在新窗口或标签页中打开

学习 if-else 语句