Next: Labeled break and continue statements. Up: More about loops. Previous: The do loop.


The continue statement

Textbook: Section 8.4

We've seen how the break statement will terminate a loop prematurely. The continue statement is related: It tells the compute to skip the body of the loop, but to test to see whether to continue through another iteration.

InputFile f = new InputFile("input");
int total = 0;
while(true) {
    String line = f.readLine();
    if(line == null) break;
    if(line.startsWith("#")) {
        IO.println("line commented out");
        continue;
    }
    total += Integer.parseInt(line);
}
System.out.println(total);
The above program sums up all the numbers in a file, but it ignores lines beginning with '#' - essentially, the '#' works as a way of adding comments to the file.

In a for loop, the update clause will still be executed when a continue statement is encountered.

InputFile f = new InputFile("input");
int total = 0;
for(int line_num = 1; ; line_num++) {
    String line = f.readLine();
    if(line == null) break;
    if(line.startsWith("#")) {
        IO.println("line " + line_num + " commented out");
        continue;
    }
    total += Integer.parseInt(line);
}
In this program, the line_num++ is executed even when the line begins with ``#.''


Next: Labeled break and continue statements. Up: More about loops. Previous: The do loop.