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."