6.8 Event-Controlled Loops Using do/while

Another form of loop that is especially useful for validating user input is the do/while loop. In the do/while loop, the loop condition is tested at the end of the loop (instead of at the beginning, as in the while loop). Thus the body of the do/while loop is executed at least once.

The syntax of the do/while loop is the following:

// initialize variables
do
{
  // body of loop
} while ( condition );
// process the results

Figure 6.13 shows the flow of control of a do/while loop.

To use the do/while loop to validate user input, we insert the prompt for the input inside the body of the loop, then use the loop condition to test the value of the input. Like the while loop, the body of the loop will be ...

Get Java Illuminated, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.