Vous êtes sur la page 1sur 57

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Liang, Introduction to Java Programming, Eighth

Edition, (c) 2011 Pearson Education, Inc. All Inc.rights reserved. 0132130807 All rights reserved. 0132130807

Accumulators

finding a sum

Counting

negative numbers prime numbers times a certain number or word occurs

Reading input

file (until the end of the file) keyboard (until a sentinel is entered)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Suppose that you need to print a string (e.g., "Welcome to Java!") a hundred times. It would be tedious to have to write the following statement a hundred times: System.out.println("Welcome to Java!"); So, how do you solve this problem?

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Problem:
System.out.println("Welcome System.out.println("Welcome System.out.println("Welcome System.out.println("Welcome System.out.println("Welcome System.out.println("Welcome 100 times to to to to to to Java!"); Java!"); Java!"); Java!"); Java!"); Java!");


System.out.println("Welcome to Java!"); System.out.println("Welcome to Java!"); System.out.println("Welcome to Java!");
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Websters Dictionary
iterate: 2) to do (something) over again or repeatedly. iterative: 1) repeating; making repetition

American Heritage Dictionary


iteration: 3) Computer Science a) The process of repeating a set of instructions a specified number of times or until a specific result is achieved. b) One cycle of a set of instructions to be repeated.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Loop
the entire loop block of code one pass through a loop block

Iteration
repeating a set of instructions one cycle of a set of repeating instructions e.g. how many iterations will this loop run for?

Loop Control Variable (LCV)


a variable used to control the number of loop iterations

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Block
a set of Java instructions that are fenced off from the surrounding code e.g. if statements, loops, main method, standalone block

Local Variable
a variable that is declared inside of a block it is visible, useable, and alive only until that block ends

Declaration vs. Initialization


datatype and variable name declare a variable the first value assigned to a variable is the initialization where a variable is declared determines its visibility and life
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Like if statements, they are controlled by boolean expressions Java has three kinds of repetition statements:
while do...while for

The programmer should choose the right kind of loop for the situation

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Keep going while some condition is true When the number of loop iterations is unknown Pretest loop structure
If test fails body does not execute Loop will execute 0 or more times

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

1. Test the boolean expression 2. True


a. Execute the statements inside the loop (the loop block) b. Go back to step 1

3. False: Go to the next statement following the loop block

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

while (<condition>) { statement(s); }

//Example: int n = 1; while (n < 100) { sum += n; n++; }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

int count = 0; while (count < 100) { System.out.println("Welcome to Java"); count++; }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

12

while (loop-continuation-condition) { // loop-body; Statement(s); }

int count = 0; while (count < 100) { System.out.println("Welcome to Java!"); count++; }


count = 0;

oop Continuation Condition? true Statement(s) (loop body)

false

(count < 100)?

false

true System.out.println("Welcome to Java!"); count++;

( )

(B)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All 13 rights reserved. 0132130807

animation

int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; }

Initialize count

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

14

animation

int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; }

(count < 2) is true

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

15

animation

int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; }

Print Welcome to Java

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

16

animation

int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; }

Increase count by 1 count is 1 now

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

17

animation

int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; }

(count < 2) is still true since count is 1

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

18

animation

int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; }

Print Welcome to Java

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

19

animation

int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; }

Increase count by 1 count is 2 now

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

20

animation

int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; }

(count < 2) is false since count is 2 now

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

21

animation

int count = 0; while (count < 2) { System.out.println("Welcome to Java!"); count++; }

The loop exits. Execute the next statement after the loop.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

22

Often the number of times a loop is executed is not predetermined. You may use an input value to signify the end of the loop. Such a value is known as a sentinel value.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

23

A sentinel-controlled loop can be implemented using a confirmation dialog. The answers Yes or No to continue or terminate the loop. The template of the loop may look as follows: int option = 0; while (option == JOptionPane.YES_OPTION) { System.out.println("continue loop"); option = JOptionPane.show onfirmDialog(null, " ontinue "); }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

24

Dont use floating-point values for equality checking in a loop control.

Since floating-point values are approximations for some values, using them could result in imprecise counter values and inaccurate results. Consider the following code for computing 1 + 0.9 + 0.8 + ... + 0.1:
double item = 1; double sum = 0; while (item != 0) { // No guarantee item will be 0 sum += item; item -= 0.1; } System.out.println(sum);

Variable item starts with 1 and is reduced by 0.1 every time the loop body is executed. The loop should terminate when item becomes 0. However, there is no guarantee that item will be exactly 0, because the floating-point arithmetic is approximated. This loop seems OK on the surface, but it is actually an infinite loop.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

25

Keep going while some condition is true When unknown number of loop iterations Posttest loop structure

If test fails loop does not execute again Loop will execute 1 or more times Body of loop executed at least once
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

general

specific

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

1. Execute the statements inside the loop (the loop block) 2. Test the boolean expression
a. True: Go back to step 1 b. False: Go to the next statement following the loop block

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

do { statement(s); }while (<condition>);

//Example: int number; int sum = 0; Scanner input = new Scanner(System.in) do{ System.out.print("Enter an int, 0 to end: "); String number = input.nextInt(); sum += number; }while (number != 0);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

When the number of loop iterations is known

loop control variable

Pretest loop structure


If test fails body does not execute Loop will execute 0 or more times

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

1. Declare and initialize the LCV 2. Test the boolean expression 3. True
a. Execute the statements inside the loop (the loop block) b. Execute the iteration expression c. Go back to step 2

4. False: Go to the next statement following the loop block

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

for (<initialization>;<test>;<iteration exp>) { statement(s); }

//Example: for (int i = 0; i < 100; i++) { System.out.println("Iteration: " + (i + 1)); }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

for (initial-action; loopcontinuation-condition; action-after-each-iteration) { // loop body; Statement(s); }


nitial Action

int i; for (i = 0; i < 100; i++) { System.out.println( "Welcome to Java!"); }


i=0

Loop ontinuation on ition true Statement(s) (loop o y) Action After Eac

false

(i < 100) true System.out.println( "Welcome to Java");

false

teration

i++

(A)

( )

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

33

animation

Declare i

int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

34

animation

int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); }

Execute initializer i is now 0

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

35

animation

int i; for (i = 0; i < 2; i++) { System.out.println( "Welcome to Java!"); }

(i < 2) is true since i is 0

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

36

animation

Print Welcome to Java

int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

37

animation

int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }

Execute adjustment statement i now is 1

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

38

animation

int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }

(i < 2) is still true since i is 1

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

39

animation

Print Welcome to Java

int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

40

animation

int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }

Execute adjustment statement i now is 2

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

41

animation

int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }

(i < 2) is false since i is 2

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

42

animation

int i; for (i = 0; i < 2; i++) { System.out.println("Welcome to Java!"); }

Exit the loop. Execute the next statement after the loop

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

43

The initial-action in a for loop can be a list of zero or more comma-separated expressions. The action-after-each-iteration in a for loop can be a list of zero or more comma-separated statements. Therefore, the following two for loops are correct.
for (int i = 1; i < 100; System.out.println(i++));

for (int i = 0, j = 0; (i + j < 10); i++, j++) { // Do something }


Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

44

If the loop-continuation-condition in a for loop is omitted, it is implicitly true. Thus the statement given below in (a), which is an infinite loop, is correct. Nevertheless, it is better to use the equivalent loop in (b) to avoid confusion:
for ( ; ; ) { // Do something }
(a) Equivalent

hile (true) { // Do something }


(b)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

45

Adding a semicolon at the end of the for clause before the loop body is a common mistake, as shown below:
Logic Error

for (int i=0; i<10; i++); { System.out.println("i is " + i); }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

46

Similarly, the following loop is also wrong:


int i=0; Logic Error while (i < 10); { System.out.println("i is " + i); i++; }

In the case of the do loop, the following semicolon is needed to end the loop.
int i=0; do { System.out.println("i is " + i); i++; orrect } while (i<10);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

47

The three forms of loop statements, while, do-while, and for, are expressively equivalent; that is, you can write a loop in any of these three forms. For example, a while loop in (a) in the following figure can always be converted into the following for loop in (b):
while (loop-continuation-condition) { // Loop body }
(a) Equivalent

for ( ; loop-continuation-condition; ) // Loop body }


(b)

A for loop in (a) in the following figure can generally be converted into the following while loop in (b) except in certain special cases (see Review Question 4.17 for one of them):
for (initial-action; loop-continuation-condition; action-after-each-iteration) { // Loop body; }
(a) Equivalent

initial-action; while (loop-continuation-condition) { // Loop body; action-after-each-iteration; }


(b)

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

48

Use the loop construct that is most intuitive and comfortable for you. In general, a for loop may be used if the number of repetitions is known 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 (sentinel value) 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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

49

Numeric errors involving floating-point numbers are inevitable. This section discusses how to minimize such errors through an example.

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

50

Java keyword Immediately ends the innermost loop that contains it. Generally used with an if statement

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

public class Test reak { public static void main(String[] args) { int sum = 0; int number = 0; while (number < 20) { number++; sum += number; if (sum >= 100) { break; } } System.out.println("The number is " + number); System.out.println("The sum is " + sum); } }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

52

Java keyword End the current iteration


NOT the entire loop Control goes to the END of the current loop body

Generally used with an if statement

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

public class Test ontinue { public static void main(String[] args) { int sum = 0; int number = 0; while (number < 20) { number++; if (number == 10 || number == 11) { continue; } sum += number; } System.out.println("The sum is " + sum); } }

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

54

Beware of infinite loops


Double-check test condition

Watch for off by 1 Perform a walk-through to check your loop

Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

The statement(s) inside of the loop are indented to indicate that relationship The use of a consistent indentation style makes a program easier to read and understand Although it makes no difference to the compiler, proper indentation is crucial
"Always code as if the person who ends up maintaining your code will be a violent psychopath who knows where you live." -- Martin Golding
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Loo for while dowhile

S nta
for (<init>; <test>; <iteration exp>) { statement(s); } while (<test>) { statement(s); } do { statement(s); }while (<test>);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved. 0132130807

Vous aimerez peut-être aussi