if (條件1)
功能代碼1;
else if (條件2)
功能代碼2;
else if (條件3)
功能代碼3;
...
else
功能代碼;
else if 為兩個關鍵字,中間有空格boolean 型別else if 可無限擴展else 可選依序判斷條件,首個為 true 的分支執行對應代碼,其餘跳過;全 false 則執行 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;
else if (month == 5) days = 31;
else if (month == 6) days = 30;
else if (month == 7) days = 31;
else if (month == 8) days = 31;
else if (month == 9) days = 30;
else if (month == 10) days = 31;
else if (month == 11) days = 30;
else if (month == 12) days = 31;
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');
// 輸出 B
關鍵細節:條件順序至關重要。若寫成 if (score >= 60) 在最前,87 分會被誤判為 D。必須從嚴格到寬鬆、從高到低排序。
if-else if-else 是通用多分支結構,但大量離散值匹配時代碼冗長。針對「一組值相等判斷」場景,switch 結構更清晰、執行略快。下一節將詳細介紹 switch。