4.4. The for Loop

 
[Page 100 ( continued )]

4.3. 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.
(This item is displayed on page 101 in the print version)


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.


[Page 101]

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 =     ;  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 } 

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 the loop if you use a while loop.


 


Introduction to Java Programming-Comprehensive Version
Introduction to Java Programming-Comprehensive Version (6th Edition)
ISBN: B000ONFLUM
EAN: N/A
Year: 2004
Pages: 503

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net