do...while Repetition Statement

The do...while repetition statement is similar to the while statement. In the while, the program tests the loop-continuation condition at the beginning of the loop, before executing the loop's body. If the condition is false, the body never executes. The do...while statement tests the loop-continuation condition after executing the loop's body; therefore, the body always executes at least once. When a do...while statement terminates, execution continues with the next statement in sequence. Figure 5.7 uses a do...while (lines 1014) to output the numbers 110.

Figure 5.7. do...while repetition statement.

1 // Fig. 5.7: DoWhileTest.java 2 // do...while repetition statement. 3 4 public class DoWhileTest 5 { 6 public static void main( String args[] ) 7 { 8 int counter = 1; // initialize counter 9 10 do 11 { 12 System.out.printf( "%d ", counter ); 13 ++counter; 14 } while ( counter <= 10 ); // end do...while 15 16 System.out.println(); // outputs a newline 17 } // end main 18 } // end class DoWhileTest  

1 2 3 4 5 6 7 8 9 10  

Line 8 declares and initializes control variable counter. Upon entering the do...while statement, line 12 outputs counter's value and line 13 increments counter. Then the program evaluates the loop-continuation test at the bottom of the loop (line 14). If the condition is true, the loop continues from the first body statement in the do...while (line 12). If the condition is false, the loop terminates and the program continues with the next statement after the loop.

Figure 5.8 contains the UML activity diagram for the do...while statement. This diagram makes it clear that the loop-continuation condition is not evaluated until after the loop performs the action state at least once. Compare this activity diagram with that of the while statement (Fig. 4.4). It is not necessary to use braces in the do...while repetition statement if there is only one statement in the body. However, most programmers include the braces, to avoid confusion between the while and do...while statements. For example,

       while ( condition )

is normally the first line of a while statement. A do...while statement with no braces around a single-statement body appears as:

      do

         statement

      while ( condition );

which can be confusing. A reader may misinterpret the last linewhile( condition );as a while statement containing an empty statement (the semicolon by itself). Thus, the do...while statement with one body statement is usually written as follows:

      do

      {

         statement

      } while ( condition );

Figure 5.8. do...while repetition statement UML activity diagram.

Good Programming Practice 5.7

Always include braces in a do...while statement, even if they are not necessary. This helps eliminate ambiguity between the while statement and a do...while statement containing only one statement.

Категории