程序流程控制結構決定代碼執行順序,是編程基礎中的基礎。Java 提供三大基本結構:順序、選擇、循環,以及異常處理結構。本文系統梳理選擇結構與條件表達式的核心知識點。
選擇結構根據條件執行不同代碼路徑,Java 提供兩種形式:
if-else 語句switch 語句| 類型 | 描述 | 示例 |
|---|---|---|
| 關係表達式 | 比較兩個同類型值,結果為 boolean | x % 2 == 0、x + y >= 0 |
| 邏輯表達式 | 邏輯運算符連接,結果為 boolean | x > 6 && y < 3、year % 4 == 0 && year % 100 != 0 || year % 400 == 0 |
| 條件運算表達式 | 三目運算符,語法:條件 ? 值1 : 值2 | max = (a > b) ? a : b |
// 塊語句形式(推薦)
if (條件) {
語句1;
} else {
語句2;
}
// 單行形式(簡單場景)
if (條件) 語句1; else 語句2;
public class LeapYearDemo {
public static void main(String[] args) {
int year = 2012;
// 閏年條件:能被4整除但不能被100整除,或能被400整除
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (isLeapYear) {
System.out.println(year + " 是閏年");
} else {
System.out.println(year + " 不是閏年");
}
}
}
if (條件1) {
語句1;
} else if (條件2) {
語句2;
} else if (條件3) {
語句3;
} else {
語句N; // 以上條件都不滿足時執行
}
{} 明確作用域,避免配對混淆
// 錯誤:else 匹配給了內層 if
if (x > 0)
if (y > 0)
System.out.println("第一象限");
else
System.out.println("x 不大於 0"); // 實際匹配內層 if!
// 正確:使用大括號明確結構
if (x > 0) {
if (y > 0) {
System.out.println("第一象限");
}
} else {
System.out.println("x 不大於 0");
}
if (isValid) 替代 if (!isInvalid)適用於多值匹配場景(Java 12+ 支援 switch 表達式):
// 傳統 switch
switch (day) {
case 1: case 2: case 3: case 4: case 5:
System.out.println("工作日");
break;
case 6: case 7:
System.out.println("週末");
break;
default:
System.out.println("無效日期");
}
// Java 12+ switch 表達式
String type = switch (day) {
case 1, 2, 3, 4, 5 -> "工作日";
case 6, 7 -> "週末";
default -> "無效日期";
};
掌握流程控制結構是編寫清晰、正確代碼的前提。建議新手多練習條件邏輯組合,養成使用大括號和提取布爾變量的好習慣。