Next: The continue statement. Up: More about loops. Previous: None.


The do loop

Textbook: Section 8.3

We've already seen the while loop and the for loop. This is the final type of loop available in Java: The do loop. It's useful when you have a while loop, but you always want the first iteration to occur. For example, you might have handled the Nim program as follows.

import csbsju.cs160.*;

public class Nim {
    public static void main(String[] args) {
        String line;
        do {
            playGame();
            IO.print("again (y/n)? ");
            line = IO.readLine();
        } while(line.startsWith("y"));
    }
}

Notice that I had to define line outside the loop. If it was declared when it is assigned a value (the line calling IO.readLine(), the variable wouldn't be visible within the condition on the following line, since that condition follows the closing brace within which the declaration would be.


Next: The continue statement. Up: More about loops. Previous: None.