introduction to java programming lecture 9 flow control : while do-while and for loops ii

24
Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

Post on 15-Jan-2016

221 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

Introduction to Java Programming

Lecture 9

Flow Control : while do-while and for loops II

Page 2: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

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

sum i

0 1

1 2

3 3

6 4

10 5

15 6

21 7

28 8

Example : Compute the sum 1 + 2 + 3 + ... + n. (for n=7)

Page 3: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

左右兩個程式結果有何不同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 = ?)

Page 4: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

可能會犯的錯誤 : 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);

廻圈很容易就會多做或少做一次,在寫判斷時要仔細想清楚

Page 5: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

另一個可能會犯的錯誤int n = 7;

int sum = 0;

int i = 1;

while (i <= n)

sum += i;

i++;

System.out.println(sum);

(if n = 7, output = ?)

Page 6: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

這也是常犯的錯誤int n = 7;

int sum = 0;int i = 1;while (i <= n);{sum += i;i++;

}System.out.println(sum);

(如果 n = 7, 結果會顯示什麼 ?)

Page 7: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

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.

Page 8: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

利用廻圈來檢查使用者的輸入

Scanner scan = new Scanner(System.in);

System.out.println("請輸入 1到 10之間的數字 :");

int num = scan.nextInt();

Scanner scan = new Scanner(System.in);int numdo{

System.out.println("請輸入 1 到 10之間的數字 :");num = scan.nextInt();

}while(num < 0 || num > 10);

如果使用者輸入了範圍之外的數字呢 ?

Page 9: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

9

Basic For Loop SyntaxFor 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. 1. initializationinitialization

2. 2. Test ConditionTest Condition 4. Update: Update 4. Update: Update the value.the value.

Note that each Note that each section is separated section is separated by a semicolon.by a semicolon.

3. 3. Loop bodyLoop body

Page 10: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

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

Page 11: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

• 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

Page 12: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

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--)

orfor (i = 0, j = 0; j + i <= 10; j++, i++)

• Commas known here as comma operators

Page 13: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

13

幾個需要注意的事情• 不要使用 float 或 double 當廻圈的判斷或計數的變數• 分清楚 , 跟 ; 在 for廻圈中的功用• 跟 if , while 一樣,在判斷後立刻加上 ; 會產生跟預

期不同的結果

int n = 7;

int sum = 0;

for (int i =1; i <= n; i++);

sum += i;

分號的影響是什麼

Page 14: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

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

Page 15: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

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) 來控制迴圈是否繼續執行 )

Page 16: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

Indefinite Loop : A while example// TestWhile.java: Test the while loopimport 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);

Page 17: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

// 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); }}

Page 18: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

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.

Page 19: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

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");

Page 20: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

break and continue

Page 21: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

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.

Page 22: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

Example of break use// TestBreak.java: Test the break keyword in the looppublic 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); }}

Page 23: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

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.

Page 24: Introduction to Java Programming Lecture 9 Flow Control : while do-while and for loops II

Example of continue// TestContinue.java: Test the continue keywordpublic 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); }}