條件語句讓程序根據布爾表達式選擇執行路徑。Java 提供 if、if-else、if-else if-else 三種形式,以及 switch 多分支(另文詳解)。
if (條件表達式)
功能語句; // 單句可無大括號
// 推薦:始終使用塊結構
if (條件表達式) {
功能語句塊; // 多語句、可讀性強、防錯
}
boolean 類型if (condition); 後加分號 = 空語句體,極易產生邏輯 Bugint a = 10;
if (a >= 0) System.out.println("a 是正數或零");
if (a % 2 == 0) System.out.println("a 是偶數");
if (條件) {
真分支語句塊;
} else {
假分支語句塊;
}
else 可選,但「防御性編程」建議寫上(即使為空),明確意圖int n = 12;
if (n % 2 != 0) {
System.out.println("n 是奇數");
} else {
System.out.println("n 不是奇數"); // 輸出此行
}
if (條件1) {
分支1;
} else if (條件2) {
分支2;
} else if (條件3) {
分支3;
}
// ... 任意多 else if
else {
默認分支; // 可選
}
int month = 3, days = 0;
if (month == 1) days = 31;
else if (month == 2) days = 28;
else if (month == 3) days = 31;
else if (month == 4) days = 30;
// ... 12 月
System.out.println(days); // 31
int score = 87;
if (score >= 90) System.out.println('A');
else if (score >= 80) System.out.println('B'); // 命中此處
else if (score >= 70) System.out.println('C');
else if (score >= 60) System.out.println('D');
else System.out.println('E');
⚠️ 若順序顛倒(如先判 >=60),87 會被誤判為 D。
if (cond1)
if (cond2)
stmt1;
else
stmt2; // 此 else 匹配「最近的未配對 if」即 cond2
✅ 解決:用大括號明確結構
if (cond1) {
if (cond2) {
stmt1;
}
} else {
stmt2; // 明確屬於 cond1
}
public void process(User u) {
if (u == null) return; // 衛語句
if (!u.isActive()) throw new IllegalStateException();
// 核心邏輯平鋪
}
if (isEligible(user)) 而非 if (user.age>18 && user.score>60 && ...)yield,Java 14+ 標準化,更適合枚舉/常值匹配| 代碼 | 問題 | 修正 |
|---|---|---|
if (a = 1) | 賦值而非比較 | if (a == 1) 或 if (1 == a) (Yoda 寫法防錯) |
if (str == "abc") | 引用比較 | if ("abc".equals(str)) |
if (list.size() > 0) | 非空判斷 | if (!list.isEmpty()) |
浮點數 == | 精度誤差 | Math.abs(a-b) < 1e-9 |