Java Reference
In-Depth Information
NOTE If you have been concentrating, you may well have noticed that you don't really need
nested loops to display the factorial of successive integers. You can do it with a single loop
that multiplies the current factorial value by the loop counter. However, this would be a very
poor demonstration of a nested loop.
The continue Statement
There are situations where you may want to skip all or part of a loop iteration. Suppose you want to sum the
values of the integers from 1 to some limit, except that you don't want to include integers that are multiples
of three. You can do this using an if and a continue statement:
for(int i = 1; i <= limit; ++i) {
if(i % 3 == 0) {
continue; // Skip the rest of this iteration
}
sum += i; // Add the current value of i to sum
}
The continue statement is executed in this example when i is an exact multiple of 3, causing the rest
of the current loop iteration to be skipped. Program execution continues with the next iteration if there is
one, and if not, with the statement following the end of the loop block. The continue statement can appear
anywhere within a block of loop statements. You may even have more than one continue in a loop.
The Labeled continue Statement
Where you have nested loops, there is a special form of the continue statement that enables you to stop
executing the inner loop — not just the current iteration of the inner loop — and continue at the beginning
of the next iteration of the outer loop that immediately encloses the current loop. This is called the labeled
continue statement.
To use the labeled continue statement, you need to identify the loop statement for the enclosing outer
loop with a statement label . A statement label is simply an identifier that is used to reference a particular
statement. When you need to reference a particular statement, you write the statement label at the beginning
of the statement in question, separated from the statement by a colon. Let's look at an example.
TRY IT OUT: Labeled continue
You could add a labeled continue statement to omit the calculation of factorials of odd numbers greater
than 10. This is not the best way to do this, but it does demonstrate how the labeled continue statement
works:
Search WWH ::




Custom Search