do-while Loops

The do-while loop is similar to the while loop, but the conditional test goes in a different place. The following is an example of a do-while loop:

do {
    // the statements inside the loop go here
} while (gameLives > 0);

Like the while loop, this loop continues looping until the gameLives variable is no longer greater than 0. The do-while loop is different because the conditional test is conducted after the statements inside the loop, instead of before them.

When the do loop is reached for the first time as a program runs, the statements between the do and while are handled automatically, and then the while condition is tested to determine whether the loop should be repeated. If the while condition is true, the loop goes around one more time. If the condition is false, the loop ends. Something must happen inside the do and while statements that changes the condition tested with while, or the loop continued indefinitely. The statements inside a do-while loop always are handled at least once.

The following statements cause a do-while loop to display the same line of text several times:

int limit = 5;
int count = 1;
do {
    System.out.println("I will not Xerox my butt");
    count++;
} while (count < limit);

Like a while loop, a do-while loop uses one or more variables that are set up before the loop statement.

The loop displays the text “I will not Xerox my butt” four times. If you gave the count variable an initial value of 6 instead of 1, the text would be displayed once, even though count is never less than limit.

In a do-while loop, the statements inside the loop are executed at least once even if the loop condition is false the first time around.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.137.75