Java Else If
else if 语句
使用 else if
语句指定一个新条件,如果第一个条件为 false
。
语法
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
示例
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
// Outputs "Good evening."
示例说明
在上面的例子中,时间 (22) 大于 10,所以第一个条件是 false
。 else if
语句中的下一个条件也是 false
,所以我们转到 else
条件,因为条件1和条件2都为 false
- 并打印到屏幕上 "Good evening"。
但是,如果时间是 14,我们的程序将打印 "Good day."