引言
流程控制是編程語言的核心邏輯結構,決定了程序的執行順序與邏輯判斷能力。本文以?分支結構、循環結構?和?隨機數生成?為核心,結合代碼示例與底層原理,全面解析Java中流程控制的應用場景與實戰技巧。
一、分支結構
1. if分支
作用:根據條件表達式的結果(true
/false
)決定代碼執行路徑。
三種形式
-
單分支?
if (條件) {// 條件為true時執行 }
-
雙分支
if (條件) {// 條件為true時執行 } else {// 條件為false時執行 }
-
多分支
if (條件1) {// 條件1為true時執行 } else if (條件2) {// 條件2為true時執行 } else {// 所有條件均不滿足時執行 }
案例:成績獎勵機制
Scanner sc = new Scanner(System.in);
System.out.print("請輸入成績:");
int score = sc.nextInt();
if (score >= 95) {System.out.println("獎勵山地自行車一輛");
} else if (score >= 90) {System.out.println("獎勵游樂場玩一次");
} else if (score >= 80) {System.out.println("獎勵變形金剛玩具一個");
} else {System.out.println("胖揍一頓");
}
2. switch分支
作用:根據表達式的值匹配具體分支執行,適合離散值比較。
語法
switch (表達式) {case 值1:// 匹配值1時執行break;case 值2:// 匹配值2時執行break;default:// 無匹配時執行
}
注意事項
-
表達式類型:支持
byte
、short
、int
、char
、String
(JDK7+)和枚舉。 -
穿透性:若未寫
break
,會繼續執行后續case
代碼。 -
case值唯一性:不能重復且必須為字面量。
案例:工作日備忘錄
String day = "周一";
switch (day) {case "周一":System.out.println("埋頭苦干,解決bug");break;case "周三":System.out.println("今晚啤酒、龍蝦、小燒烤");break;default:System.out.println("按部就班工作");
}
二、循環結構
1. for循環
作用:已知循環次數時,控制代碼重復執行。
語法
for (初始化語句; 循環條件; 迭代語句) {// 循環體
}
案例:求1-100的偶數和
int sum = 0;
for (int i = 1; i <= 100; i++) {if (i % 2 == 0) {sum += i;}
}
System.out.println("偶數和:" + sum);
2. while循環
作用:不確定循環次數時,根據條件重復執行代碼。
語法
初始化語句;
while (循環條件) {// 循環體迭代語句;
}
案例:紙張折疊成珠峰高度
double peakHeight = 8848860; // 珠峰高度(毫米)
double paperThickness = 0.1; // 紙張厚度(毫米)
int count = 0;
while (paperThickness < peakHeight) {paperThickness *= 2;count++;
}
System.out.println("需折疊次數:" + count);
3. do-while循環
特點:先執行循環體,再判斷條件,至少執行一次。
語法
初始化語句;
do {// 循環體迭代語句;
} while (循環條件);
案例:用戶菜單選擇
Scanner sc = new Scanner(System.in);
int choice;
do {System.out.println("1.登錄 2.注冊 3.退出");choice = sc.nextInt();
} while (choice != 3);
三、跳轉關鍵字
1. break
作用:立即終止當前循環或switch
分支。
案例:密碼驗證
Scanner sc = new Scanner(System.in);
int correctPwd = 520;
while (true) {System.out.print("請輸入密碼:");int input = sc.nextInt();if (input == correctPwd) {System.out.println("歡迎進入系統");break;} else {System.out.println("密碼錯誤");}
}
2. continue
作用:跳過當前循環的剩余代碼,進入下一次迭代。
案例:輸出1-10的非偶數
for (int i = 1; i <= 10; i++) {if (i % 2 == 0) {continue;}System.out.println(i);
}
四、隨機數生成(Random類)
1. 基本使用
步驟:
-
導包:
import java.util.Random;
-
創建對象:
Random r = new Random();
-
生成隨機數:
int num = r.nextInt(范圍);
案例:生成1-100隨機數
Random r = new Random();
int number = r.nextInt(100) + 1; // 1-100
System.out.println("隨機數:" + number);
2. 猜數字游戲
Random r = new Random();
int target = r.nextInt(100) + 1;
Scanner sc = new Scanner(System.in);
while (true) {System.out.print("請輸入猜測數字(1-100):");int guess = sc.nextInt();if (guess > target) {System.out.println("過大");} else if (guess < target) {System.out.println("過小");} else {System.out.println("猜中了!");break;}
}
五、總結
-
分支結構:
if
適合區間判斷,switch
適合離散值匹配。 -
循環結構:
for
用于已知次數,while
用于未知次數,do-while
至少執行一次。 -
跳轉關鍵字:
break
終止循環,continue
跳過當前迭代。 -
Random類:靈活生成指定范圍的隨機數,增強程序交互性。
學習建議:
-
多練習循環嵌套(如打印九九乘法表)。
-
結合實際問題設計分支邏輯(如用戶權限驗證)。
-
嘗試實現復雜交互邏輯(如猜數字游戲的難度分級)。