Documentation

The Java™ Tutorials
Hide TOC
The if-then and if-then-else Statementsif-then和if-then-else语句
Trail: Learning the Java Language
Lesson: Language Basics
Section: Control Flow Statements

The if-then and if-then-else Statementsif-then语句和if-then-else语句

The if-then Statementif-then语句

The if-then statement is the most basic of all the control flow statements.if-then语句是所有控制流语句中最基本的。It tells your program to execute a certain section of code only if a particular test evaluates to true.它告诉您的程序只有在特定测试的计算结果为true时才执行特定的代码段。For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion.例如,只有当自行车已经在运动时,Bicycle类才允许制动器降低自行车的速度。One possible implementation of the applyBrakes method could be as follows:applyBrakes方法的一个可能实现如下:

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

If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-then statement.如果此测试的结果为false(表示自行车没有运动),则控制跳到if-then语句的末尾。

In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement:此外,如果“then”子句只包含一条语句,则开始括号和结束括号是可选的:

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

Deciding when to omit the braces is a matter of personal taste.决定何时省略花括号是个人喜好的问题。Omitting them can make the code more brittle.省略它们会使代码更加脆弱。If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces.如果后来在“then”子句中添加了第二条语句,那么一个常见的错误就是忘记添加新需要的花括号。The compiler cannot catch this sort of error; you'll just get the wrong results.编译器无法捕获此类错误;你只会得到错误的结果。

The if-then-else Statementif-then-else语句

The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false.当“if”子句的计算结果为false时,if-then-else语句提供了执行的辅助路径。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.如果在自行车不运动时踩下制动器,可以在applyBrakes方法中使用if-then-else语句来采取一些措施。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.以下程序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);
    }
}

The output from the program is:程序的输出为:

Grade = C

You may have noticed that the value of testscore can satisfy more than one expression in the compound statement: 76 >= 70 and 76 >= 60.您可能已经注意到testscore的值可以满足复合语句中的多个表达式:76 >= 7076>=60However, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated.但是,一旦满足条件,就会执行相应的语句(grade = 'C';)其余条件不进行评估。


Previous page: Control Flow Statements
Next page: The switch Statement