Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Intro_Java_brief_Liang2011.pdf
Скачиваний:
195
Добавлен:
26.03.2016
Размер:
10.44 Mб
Скачать

124 Chapter 4 Loops

Caution

Don’t use floating-point values for equality checking in a loop control. Since floating-point values numeric error are approximations for some values, using them could result in imprecise counter values and inac-

curate 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.

4.2.5Input and Output Redirections

In the preceding example, if you have a large number of data to enter, it would be cumbersome to type from the keyboard. You may store the data separated by whitespaces in a text file, say input.txt, and run the program using the following command:

java SentinelValue < input.txt

input redirection

This command is called input redirection. The program takes the input from the file

 

input.txt rather than having the user to type the data from the keyboard at runtime. Suppose

 

the contents of the file are

 

 

 

 

 

2 3 4 5 6 7 8 9 12 23 32

 

 

 

 

23

45 67

89 92 12

34 35

3

1

2 4 0

 

The program should get sum to be 518.

output redirection

Similarly, there is output redirection, which sends the output to a file rather than displaying

 

it on the console. The command for output redirection is:

 

java ClassName > output.txt

 

 

Input and output redirection can be used in the same command. For example, the following

 

command gets input from input.txt and sends output to output.txt:

 

java SentinelValue < input.txt > output.txt

 

Please run the program and see what contents are in output.txt.

 

4.3 The do-while Loop

 

The do-while loop is a variation of the while loop. Its syntax is given below:

do-while loop

do {

 

// Loop body;

 

Statement(s);

 

} while (loop-continuation-condition);

Its execution flow chart is shown in Figure 4.2.

4.3 The do-while Loop 125

loop- true continuation

false

FIGURE 4.2 The do-while loop executes the loop body first, then checks the loop- continuation-condition to determine whether to continue or terminate the loop.

The loop body is executed first. Then the loop-continuation-condition is evaluated. If the evaluation is true, the loop body is executed again; if it is false, the do-while loop terminates. The difference between a while loop and a do-while loop is the order in which the loop-continuation-condition is evaluated and the loop body executed. The while loop and the do-while loop have equal expressive power. Sometimes one is a more convenient choice than the other. For example, you can rewrite the while loop in Listing 4.4 using a do-while loop, as shown in Listing 4.5:

LISTING 4.5 TestDoWhile.java

1 import java.util.Scanner;

2

3 public class TestDoWhile {

4/** Main method */

5 public static void main(String[] args) {

6int data;

7 int sum = 0;

8

9// Create a Scanner

10 Scanner input = new Scanner(System.in);

11

12// Keep reading data until the input is 0

13do {

14// Read the next data

15System.out.print(

16"Enter an int value (the program exits if the input is 0): ");

17data = input.nextInt();

18

19sum += data;

20} while (data != 0);

21

22System.out.println("The sum is " + sum);

23}

24}

Enter an int value (the program exits if the input is 0): 3

Enter an int value (the program exits if the input is 0): 5

Enter an int value (the program exits if the input is 0): 6

Enter an int value (the program exits if the input is 0): 0 The sum is 14

loop

end loop

126 Chapter 4 Loops

Tip

Use the do-while loop if you have statements inside the loop that must be executed at least once, as in the case of the do-while loop in the preceding TestDoWhile program. These statements must appear before the loop as well as inside it if you use a while loop.

4.4 The for Loop

Often you write a loop in the following common form:

i = initialValue; // Initialize loop control variable while (i < endValue) {

// Loop body

...

i++; // Adjust loop control variable

}

A for loop can be used to simplify the proceding loop:

 

for (i = initialValue; i < endValue; i++) {

 

// Loop body

 

...

 

}

 

In general, the syntax of a for loop is as shown below:

for loop

for (initial-action; loop-continuation-condition;

 

action-after-each-iteration) {

 

// Loop body;

 

Statement(s);

 

}

 

The flow chart of the for loop is shown in Figure 4.3(a).

Initial-Action

loop-

false

continuation

 

condition?

 

true

 

Statement(s)

 

(loop body)

 

action-after-each-iteration

(a)

 

i = 0

 

(i < 100)?

false

 

true

 

System.out.println(

 

"Welcome to Java");

i++

 

(b)

 

FIGURE 4.3 A for loop performs an initial action once, then repeatedly executes the statements in the loop body, and performs an action after an iteration when the loop- continuation-condition evaluates to true.

4.4 The for Loop 127

The for loop statement starts with the keyword for, followed by a pair of parentheses enclosing the control structure of the loop. This structure consists of initial-action, loop-continuation-condition, and action-after-each-iteration. The control structure is followed by the loop body enclosed inside braces. The initial-action, loop- continuation-condition, and action-after-each-iteration are separated by semicolons.

A for loop generally uses a variable to control how many times the loop body is executed

and when the loop terminates. This variable is referred to as a control variable. The initial- control variable action often initializes a control variable, the action-after-each-iteration usually

increments or decrements the control variable, and the loop-continuation-condition tests whether the control variable has reached a termination value. For example, the following for loop prints Welcome to Java! a hundred times:

int i;

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

}

The flow chart of the statement is shown in Figure 4.3(b). The for loop initializes i to 0, then repeatedly executes the println statement and evaluates i++ while i is less than 100.

The initial-action, i = 0, initializes the control variable, i. The loop- continuation-condition, i < 100, is a Boolean expression. The expression is evaluated right after the initialization and at the beginning of each iteration. If this condition is true, the loop body is executed. If it is false, the loop terminates and the program control turns to the line following the loop.

The action-after-each-iteration, i++, is a statement that adjusts the control variable. This statement is executed after each iteration. It increments the control variable. Eventually, the value of the control variable should force the loop-continuation-condition to become false. Otherwise the loop is infinite.

The loop control variable can be declared and initialized in the for loop. Here is an example:

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

}

If there is only one statement in the loop body, as in this example, the braces can be omitted.

Tip

The control variable must be declared inside the control structure of the loop or before the loop. If the loop control variable is used only in the loop, and not elsewhere, it is good programming practice to declare it in the initial-action of the for loop. If the variable is declared inside the loop control structure, it cannot be referenced outside the loop. In the preceding code, for example, you cannot reference i outside the for loop, because it is declared inside the for loop.

initial-action

action-after-each- iteration

omitting braces

declare control variable

Note

The initial-action in a for loop can be a list of zero or more comma-separated variable

for loop variations

declaration statements or assignment expressions. For example,

 

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

}

The action-after-each-iteration in a for loop can be a list of zero or more commaseparated statements. For example,

for (int i = 1; i < 100; System.out.println(i), i++ );

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]