控制流程 邏輯判斷 迴圈控制
流程控制結構 流程控制結構(Control Structure)- 傳統的程式設計概念以結構化程式設計(Structured Programming)為基礎,使用由上而下的設計(Top-down Design)來分析問題 將程式分解成階層架構(Hierarchical Architecture)的模組(Module),每個模組擁有獨立功能的程式碼,只有單一的進入點和離開點 用循序(Sequential)、選擇(Selection)及迭代(Iteration)等三種流程控制結構來整合 循序-宣告變數→取得初始值→資料運算→輸出結果 選擇-if … else邏輯判斷設定不同條件之進入點 迭代-for, while, do…while迴圈流程重複相同的運算程序
邏輯判斷-條件控制敘述(Conditional Control) if是否選擇條件敘述 if (比較式) { 比較式成立時 執行此區段; }
if...else二選一條件敘述 if (比較式){ 執行區段1; } else { 執行區段2; }
比較式之邏輯概念 比較式亦可直接代入布林變數(或布林值) 等式:== , equals() 數值判斷:a == b, b == 10 字元判斷:c == ‘A’ 字串判斷:str.equals(“Tom”), str1.equals(str2) 不等式:>, <, >=, <=, <>, !=, !equals() 數值判斷:a > b, b < 10.5, a >= b, a <= 10, a <> 0, d != 5 字元判斷:c < ‘K’, c1 <> c2, c0 != ‘O’ 字串判斷:!str.equals(“Mary”) 邏輯比較:&&, ||, ! 且(AND):(a > b) && str1.equals(str2) 或(OR):(c==‘A’) || b<>7 非(NOT):!(b <= a), !str.equals(“Mary”) 比較式亦可直接代入布林變數(或布林值) if(true), if(false)
if...else if...else多選一條件敘述 if (比較式1){ 執行區段1 }elseif (比較式2){ 執行區段2 }else{ 執行區段 }
switch多選一條件敘述(下式中case後的比較值為單一字元或整數) switch(變數) { case 比較值1: 執行區段; break; case 比較值2: 執行區段; break; : default: 執行區段; }
條件控制範例 public class Ex02_ControlFlow { public static void main(String[] args) { // TODO code application logic here int score = 60; // if條件敘述 System.out.println("Score: " + score); if ( score >= 60 ) { System.out.print("JavaSE Design"); System.out.println("Pass!:)"); } score = 56; if ( score < 60 ) System.out.println("Failed!:("); // if-else條件敘述 } else { 條件控制範例
String stage = "baby"; // if-else if-else多選一條件敘述 System.out.println("Passenger Stage: " + stage); if (stage.equals("student")) System.out.println("Student Rate: NT$12"); else if (stage.equals("senior")) System.out.println("Senior Rate: NT$8"); else if(stage.equals("baby")) System.out.println("Baby Rate: Free") ; else System.out.println("Regular Rate: NT$15"); int age = 40; // if-else多選一條件敘述 System.out.println("Passenger Age: " + age); if ( age <= 18 && !stage.equals("baby")) if ( age >= 65 || stage.equals("senior")) System.out.println("Baby Rage: Free") ;
// switch多選一條件敘述 char grade = 'C'; System.out.println("Student GPA: " + grade); switch (grade) { case 'A': System.out.println("The Score Passing 80 points"); break; case 'B': System.out.println("The Score Between 70~79 points"); case 'C': System.out.println("The Score Between 60~69 points"); default: System.out.println("The Score Under 60 points"); }
迴圈控制敘述(Loop Control) for迴圈敘述- for(計數起始條件;計數終止條件; 計數累進) { 執行區段; } 執行迴圈前後不檢查條件運算式,又稱計數迴圈(counting loop) ex: 計算sum = 1 + 2 + … + 100 int sum = 0; for(int i=1; i<=100; i++) { sum = sum + i ; }
while迴圈敘述- while(條件運算式) { 執行區段; } 執行迴圈前檢查條件運算式,直到不符合條件時離開回圈 ex: 計算sum = 1 + 2 + … + 100 int sum = 0, count = 1 ; while(count <= 100) { sum = sum + count ; count ++ ; }
do … while迴圈敘述- do { 執行區段; } while (條件運算式) ; 執行迴圈後檢查條件運算式,直到不符合條件時離開迴圈,故迴圈一定會執行第一次 ex: 計算sum = 1 + 2 + … + 100 int sum = 0, count = 0 ; do { count ++ ; sum = sum + count ; }while(count<=100);
巢式迴圈- 迴圈中包含迴圈,可以前述三種迴圈形式交互應用 利用break敘述跳出一層迴圈 ex: 列印九九乘法表 for(int i=1; i<=9; i++) { for(int j=1; j<=9; j++) { int prod = i*j ; System.out.print(i + “*” + j + “=” + prod + “\t”) ; } System.out.print(“\n”) ; } ex: 計算n階乘(n!),輸入n值計算連乘積,但n=0時自動離開迴圈並使連乘積為1 Scanner sc = new Scanner(System.in) ; int n = sc.nextInt() ; int count = 0, prod = 1; do { count ++ ; if(n==0) break ; prod = prod * count ; } while (count<=n) ;
迴圈控制範例 public class Ex02_LoopControl { public static void main(String[] args) { // 測試for迴圈 int total = 0; // 遞增for迴圈敘述 for (int i = 1; i <= 10; i++ ) { System.out.print("Number: " + i + " "); total += i; } System.out.println("\nSummary from 1 to 10: " + total); System.out.println(" ----------------- "); total = 0; // 重設總和變數 // 遞減for迴圈敘述 for (int i = 10; i >= 1; i-- ) { System.out.println("\nSummary from 10 to 1: " + total);
// 溫度對照表 double c = 30; double f; System.out.println("C F"); // while迴圈敘述 while ( c <= 100 ) { f = (9.0 * c) / 5.0 + 32.0; System.out.println(c + " " + f); c += 10; } // 繩索對折次數計算 int count = 0; // 計算次數 float len = 100.0f; // do/while迴圈敘述 do { System.out.println(count + " Length: " + len); count++; len /= 2.0; // 對折繩索 } while ( len > 20.0 ); System.out.println("Folding Number: " + count); System.out.println("Final Length: " + len);
// 浮點數迭加 – 誤差累計 double d=0.1; double sum=0.0; while(d<=10){ sum=sum+d; System.out.println(d +"\t"+sum + "\t" + Math.round(sum*100)/100.0); d = d + 0.1; } // 階乘計算 – 計算5! int prod = 1 ; int num = 5 count = 1; // do/while迴圈敘述 do { System.out.println("Number: " + num); if (num == 0) break ; // 跳出迴圈 else prod *= count; count++; } while ( count <= num ); System.out.println("5! = " + prod);
// 樂透彩自動選號 int lo1, lo2, lo3, lo4, lo5, lo6 ; boolean check ; int k = 1; do { lo1 = ((int)(Math.random() * 1000)) % 49 + 1; lo2 = ((int)(Math.random() * 1000)) % 49 + 1; lo3 = ((int)(Math.random() * 1000)) % 49 + 1; lo4 = ((int)(Math.random() * 1000)) % 49 + 1; lo5 = ((int)(Math.random() * 1000)) % 49 + 1; lo6 = ((int)(Math.random() * 1000)) % 49 + 1; check = false; if(lo1 == lo2 || lo1 == lo3 || lo1 == lo4 || lo1 == lo5 || lo1 == lo6 || lo2 == lo3 || lo2 == lo4 || lo2 == lo5 || lo2 == lo6 || lo3 == lo4 || lo3 == lo5 || lo4 == lo5 || lo4 == lo5 || lo4 == lo6 || lo5 == lo6) check = true ; k++ ; } while(check) ; System.out.println("重號次數:" + k + "\n" + "樂透號碼:" + lo1 + "\t" + lo2 + "\t" + lo3 + "\t" + lo4 + "\t" + lo5 + "\t" + lo6 + "\n") ;
// 九九乘法表 // 顯示標題列 System.out.print(" "); for (int i = 1; i <= 9; i++ ) System.out.print(i + " "); System.out.println(); // 巢狀迴圈-第一層while迴圈 int row = 0, col=0 ; while (row <= 9 ) { // 顯示欄標題 System.out.print(row + " "); for (col = 1; col <= 9; col++ ) { // 第二層for迴圈 System.out.print(row + "*" + col + "="); System.out.print(row*col + " "); if ( (row*col ) < 10 && col != 1 ) System.out.print(" ");// 調整顯示位置 } row++; // 計數器變數加一