程式流程由一連串陳述句組成。Java 提供豐富的流程控制陳述句,主要分三大類:分支、迴圈、例外處理。
if (boolean表達式) {
陳述句1;
} else {
陳述句2;
}
重點:
boolean 型別 (比 C/C++ 嚴格){},利擴充與閱讀else if 鏈結public class CompareTwo {
public static void main(String[] args) {
double d1 = 23.4, d2 = 35.1;
if (d2 >= d1)
System.out.println(d2 + " >= " + d1);
else
System.out.println(d1 + " >= " + d2);
}
}
public class LeapYear {
public static void main(String[] args) {
// 寫法 1:單一邏輯表達式
int year = 1989;
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
System.out.println(year + " is leap");
else
System.out.println(year + " not leap");
// 寫法 2:else if 鏈結
year = 2000;
boolean leap;
if (year % 4 != 0) leap = false;
else if (year % 100 != 0) leap = true;
else if (year % 400 != 0) leap = false;
else leap = true;
// 寫法 3:巢狀 if 配合 {}
year = 2050;
if (year % 4 == 0) {
if (year % 100 == 0) {
if (year % 400 == 0) leap = true;
else leap = false;
} else leap = true;
} else leap = false;
}
}
switch (表達式) {
case 值1: 陳述句1; break;
case 值2: 陳述句2; break;
...
default: 預設陳述句;
}
規則:
byte, short, int, char (JDK 7+ 支援 String)case 值必須為常數且互不相同break 結束該分支,避免貫穿case 共用邏輯可省略 breakchar grade = 'C';
switch (grade) {
case 'A': System.out.println("85-100"); break;
case 'B': System.out.println("70-84"); break;
case 'C': System.out.println("60-69"); break;
case 'D': System.out.println("<60"); break;
default: System.out.println("error");
}
// 輸出:60-69
while (條件) { 陳述句; }
先判斷再執行,可能零次。
do { 陳述句; } while (條件);
先執行再判斷,至少一次。
for (初始化; 條件; 更新) { 陳述句; }
適用於已知次數迴圈。JDK 5+ 支援增強型 for (for (型別 變數 : 集合))。
break:跳出最內層迴圈或 switchcontinue:跳過本次迴圈剩餘,直接進入下一次判斷try {
// 可能拋出例外的程式碼
} catch (ExceptionType1 e) {
// 處理 ExceptionType1
} catch (ExceptionType2 e) {
// 處理 ExceptionType2
} finally {
// 無論是否發生例外皆執行 (資源釋放等)
}
關鍵點:
catch 由上而下匹配,子類別例外須置於父類別之前throw 主動拋出例外throws 宣告方法可能拋出的例外// 單行註解/* 多行註解 *//** 文件註解 */ (可由 javadoc 產生 API 文件)熟練掌握流程控制是程式設計基石。建議多練習:
if-else 處理複雜條件邏輯switch 簡化多重固定值判斷for/while 處理重複性工作try-catch-finally 資源管理習慣