if (比較表達式1) {
語句體1;
} else if (比較表達式2) {
語句體2;
} else if (比較表達式3) {
語句體3;
}
...
else {
語句體n+1;
}
依序評估各比較表達式,若為 true 則執行對應語句體並結束整個 if 結構;若所有表達式皆為 false,則執行最終 else 區塊(建議保留以處理異常值)。
import java.util.Scanner;
public class DemoIf {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("請輸入成績 (0-100):");
int score = sc.nextInt();
if (score > 100 || score < 0) {
System.out.println("輸入錯誤:成績超出範圍");
} else 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 等");
}
}
}
}
switch (表達式) {
case 值1:
語句體1;
break;
case 值2:
語句體2;
break;
...
default:
語句體n+1;
break;
}
byte, short, char, int(可隱式提升為 int)Byte, Short, Character, IntegerString(JDK 1.7+)先計算表達式的值,再依序與各 case 常數比對;匹配成功則執行該區塊直到遇到 break 或結束;若無匹配則執行 default。
import java.util.Scanner;
public class DemoSwitch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.println("請輸入星期數字 (1-7):");
int week = sc.nextInt();
switch (week) {
case 1: System.out.println("星期一"); break;
case 2: System.out.println("星期二"); break;
case 3: System.out.println("星期三"); break;
case 4: System.out.println("星期四"); break;
case 5: System.out.println("星期五"); break;
case 6: System.out.println("星期六"); break;
case 7: System.out.println("星期日"); break;
default: System.out.println("輸入錯誤,請重新輸入");
}
}
}
}
| 維度 | if-else | switch |
|---|---|---|
| 判斷類型 | 布林表達式、區間、範圍 | 離散的常數值、等值比較 |
| 適用場景 | 區間判斷、複雜邏輯條件 | 固定值匹配、選單選項、狀態碼 |
| 可讀性 | 條件多時較冗長 | 結構清晰、易維護 |
| 效能 | 逐條評估 | 編譯器優化為跳躍表,O(1) 查找 |
核心原則: 能用 switch 的場景優先考慮 switch;需判斷區間、範圍或複雜布林邏輯時使用 if-else。switch 能做的 if 都能做,但反過來不成立。