Friday, November 18, 2011

Java (The do-while Loop)


The do-while Loop

The do-while loop is a variation of the while loop. Its syntax is given below:
do {
  // Loop body;
  Statement(s);
} while (loop-continuation-condition);

Its execution flow chart is shown in Figure 4.4.


Figure 4.4. The do-while loop executes the loop body first, and 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 major 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.2 using a do-while loop, as shown in Listing 4.3.

Listing 4.3. TestDo.java

 1 import javax.swing.JOptionPane;
 2
 3 public class TestDoWhile {
 4   /** Main method */
 5   public static void main(String[] args) {
 6     int data;
 7     int sum = 0;
 8
 9     // Keep reading data until the input is 0
10     do {
11       // Read the next data
12       String dataString = JOptionPane.showInputDialog(null,
13         "Enter an int value:\n(the program exits if the input is 0)",
14         "TestDo", JOptionPane.QUESTION_MESSAGE);
15
16       data = Integer.parseInt(dataString);
17
18       sum += data;
19     } while (data != 0);
20
21     JOptionPane.showMessageDialog(null, "The sum is " + sum,
22       "TestDo", JOptionPane.INFORMATION_MESSAGE);
23  }
24 }

No comments:

Post a Comment