Java Tutorial/Statement Control/Continue Statement
Содержание
Calculating Primes: using continue statement and label
continue may be followed by a label to identify which enclosing loop to continue to.
<source lang="java">
public class MainClass {
public static void main(String[] args) { int nValues = 50; OuterLoop: for (int i = 2; i <= nValues; i++) { for (int j = 2; j < i; j++) { if (i % j == 0) { continue OuterLoop; } } System.out.println(i); } }
}</source>
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
The continue Statement
The continue statement stops the execution of the current iteration and causes control to begin with the next iteration.
For example, the following code prints the number 0 to 9, except 5.
<source lang="java">
public class MainClass {
public static void main(String[] args) { for (int i = 0; i < 10; i++) { if (i == 5) { continue; } System.out.println(i); } }
}</source>
The continue statement: skips all or part of a loop iteration
<source lang="java">
public class MainClass {
public static void main(String[] arg) { int limit = 10; int sum = 0; for (int i = 1; i <= limit; i++) { if (i % 3 == 0) { continue; } sum += i; } System.out.println(sum); }
}</source>
37
The Labeled continue statement
<source lang="java">
public class MainClass {
public static void main(String[] args) { int limit = 20; int factorial = 1; OuterLoop: for (int i = 1; i <= limit; i++) { factorial = 1; for (int j = 2; j <= i; j++) { if (i > 10 && i % 2 == 1) { continue OuterLoop; } factorial *= j; } System.out.println(i + "! is " + factorial); } }
}</source>
1! is 1 2! is 2 3! is 6 4! is 24 5! is 120 6! is 720 7! is 5040 8! is 40320 9! is 362880 10! is 3628800 12! is 479001600 14! is 1278945280 16! is 2004189184 18! is -898433024 20! is -2102132736