Java Else If 语句
else if 语句
如果第一个条件为false,则使用else if语句指定一个新的条件。
语法
if (condition1) {
// 如果条件1为真,则要执行的代码块
} else if (condition2) {
// 如果条件1为假且条件2为真,则执行以下代码块。
} else {
// 如果条件1和条件2都为假,则要执行的代码块
}
想想现实生活:如果下雨,带把伞。如果阳光明媚,戴上太阳镜。否则,就正常出门。
示例
int weather = 2; // 1 = raining, 2 = sunny, 3 = cloudy
if (weather == 1) {
System.out.println("Bring an umbrella.");
} else if (weather == 2) {
System.out.println("Wear sunglasses.");
} else {
System.out.println("Just go outside normally.");
}
// Outputs "Wear sunglasses."
由于weather的值为2,第一个条件(weather == 1)不满足,因此跳过if代码块。
程序随后检查else if条件(weather == 2),该条件为true。这意味着else if代码块执行并打印"Wear sunglasses."(戴太阳镜。)
另一个示例
此示例根据一天中的不同时间,在三种不同的消息中选择一种显示:
示例
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."
Example explained
在上面的例子中,时间(22)大于 10,因此第一个条件为 false。下一个条件,在 else if 语句中,也是 false,所以我们继续执行 else 条件,因为 condition1 和 condition2 都为 false - 并在屏幕上打印"Good evening."。
但是,如果时间是 14 点,我们的程序会打印"Good day."
示例
int time = 14;
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 day."

