Download presentation
Presentation is loading. Please wait.
2
Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II
3
Basic while Loop int sum = 0; int i = 1; while (i <= 7) { sum += i; i++; } 1. Initialization 2. Test Condition 4. Update: In this case, you can use either the pre or post increment operator. 3. Loop body sumi 01 12 33 64 105 156 217 288 Example : Compute the sum 1 + 2 + 3 +... + n. (for n=7)
4
左右兩個程式結果有何不同 int n = 7; int sum = 0; int i = 1; while (i <= n) { sum += i; i++; } System.out.println(sum); (if n = 7, output = 28) int n = 7; int sum = 0; int i = 1; while (i <= n) { i++; sum += i; } System.out.println(sum); (if n = 7, output = ?)
5
可能會犯的錯誤 : 1+2+3+4+5+6+7? int n = 7; int sum = 0; int i = 1; while (i < n) { sum += i; i++; } System.out.println(sum); 廻圈很容易就會多做或少做一次, 在寫判斷時要仔細想清楚
6
另一個可能會犯的錯誤 int n = 7; int sum = 0; int i = 1; while (i <= n) sum += i; i++; System.out.println(sum); (if n = 7, output = ?)
7
這也是常犯的錯誤 int n = 7; int sum = 0; int i = 1; while (i <= n); { sum += i; i++; } System.out.println(sum); ( 如果 n = 7, 結果會顯示什麼 ?)
8
Basic do/while Loop Example : Compute the sum 1 + 2 + 3 +... + n. (for n=7) int sum = 0; int i = 1; do { sum += i; i++; } while (i <= n); System.out.println(sum); 1 Initialization 4 Test Condition 2 Loop body 3 Update: In this case, you can use either the pre or post increment operator.
9
利用廻圈來檢查使用者的輸入 Scanner scan = new Scanner(System.in); System.out.println(" 請輸入 1 到 10 之間的數字 :"); int num = scan.nextInt(); Scanner scan = new Scanner(System.in); int num do{ System.out.println(" 請輸入 1 到 10 之間的數字 :"); num = scan.nextInt(); }while(num 10); 如果使用者輸入了範圍之外的數字呢 ?
10
9 Basic For Loop Syntax For loops are good for creating definite loops. int n = 7; int sum = 0; for (int i =1; i <= n; i++) sum += i; System.out.println(sum); 1. initialization 2. Test Condition 4. Update: Update the value. Note that each section is separated by a semicolon. 3. Loop body
11
10 for Loop Variations Update may be negative: for (i = 100; i >= 1; i--) –This counts from 100 to 1. Update may be greater than 1: for (i = 100; i >= 5; i -= 5) –This counts from 100 to 5 in steps of 5
12
Arithmetic expressions –Initialization, loop-continuation, and increment can contain arithmetic expressions. If x equals 2 and y equals 10 for ( j = x; j <= 4 * x * y; j += y / x ) is equivalent to for ( j = 2; j <= 80; j += 5 ) for Loop Variations
13
12 The Comma Operator Commas known here as comma operators by using commas, you can put more than one statement in any expression for (i = 100, y = 0; i >= 1; i--) or for (i = 0, j = 0; j + i <= 10; j++, i++) Commas known here as comma operators
14
13 幾個需要注意的事情 不要使用 float 或 double 當廻圈的判斷或計數的變數 分清楚, 跟 ; 在 for 廻圈中的功用 跟 if, while 一樣,在判斷後立刻加上 ; 會產生跟預期 不同的結果 int n = 7; int sum = 0; for (int i =1; i <= n; i++); sum += i; 分號的影響是什麼
15
Loop types Indefinite Loop ( 不定次數的迴圈 ) : –You do not know ahead of time how many times your loop will execute. –For example, you do not know how many books a person might order. Definite Loop ( 固定次數的迴圈 ) : –You know exactly how many times you want the loop to execute. –not at compile time necessarily
16
Counter- and Sentinel-controlled repetition Counter Controlled Repetition : ( 利用 “ 計數器 ” 來控制迴圈是否繼續執行,用於固定次數 迴圈 ) –Simply means that we use a counter to tell you when to stop repeating a statement or group of statements However, what if we want the user to decide when to end the program? –Use a sentinel (sentinel control, user control) ( 如果要由程式使用者控制,利用 sentinel 或 flag ,其 實就是設一個控制的變數,利用設定、判斷此變數為 1 或 0 (true or false) 來控制迴圈是否繼續執行 )
17
Indefinite Loop : A while example // TestWhile.java: Test the while loop import javax.swing.JOptionPane; public class TestWhile { public static void main(String[ ] args) { int data; int sum = 0; // Read an initial data String dataString = JOptionPane.showInputDialog(null, "Enter an int value, \nthe program exits if the input is 0“); data = Integer.parseInt(dataString);
18
// Keep reading data until the input is 0 while (data != 0) { sum += data; // Read the next data dataString = JOptionPane.showInputDialog(null, "Enter an int value, \nthe program exits if the input is 0" ); data = Integer.parseInt(dataString); } JOptionPane.showMessageDialog(null, "The sum is " + sum); System.exit(0); }
19
Which Loop to Use? The three forms of loop statements, while, do, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. I recommend that you use the one that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known, as, for example, when you need to print a message 100 times. A while loop may be used if the number of repetitions is not known, as in the case of reading the numbers until the input is 0. A do-while loop can be used to replace a while loop if the loop body has to be executed before testing the continuation condition.
20
Nested loops 廻圈中的廻圈 Example: How many times is JAVA printed out? for (int i = 1; i <= 7; i++) for (int j = 1; j <= 7; j++) System.out.println("JAVA"); for (int i = 1; i <= 7; i++) for (int j = i; j <= 7; j++) System.out.println("JAVA");
21
break and continue
22
break We have seen the keyword break used in a switch statement: switch (userInput) { case 1: userInput++; break; } You can also use break inside of a for, while or do/while loop to immediately exit from the loop.
23
Example of break use // TestBreak.java: Test the break keyword in the loop public class TestBreak { /** Main method */ public static void main(String[] args) { int sum = 0; int item = 0; while (item < 5) { item ++; sum += item; if (sum >= 6) break; } System.out.println("The sum is " + sum); }
24
continue Continue is a statement which can be used inside a for, while or do/while loop in order to skip the rest of the remaining code in the loop, and start the next iteration.
25
Example of continue // TestContinue.java: Test the continue keyword public class TestContinue { /** Main method */ public static void main(String[] args) { int sum = 0; int item = 0; while (item < 5) { item++; if (item == 2) continue; sum += item; } System.out.println("The sum is " + sum); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.