java之Continue解析

有时强迫一个循环提早反复是有用的。也就是,你可能想要继续运行循环,但是要忽略这次重复剩余的循环体的语句。

continue 语句是break语句的补充。

在while 和do while 循环中,continue 语句使控制直接转移给控制循环的条件表达式,然后继续循环过程。

在for 循环中,循环的反复表达式被求值,然后执行条件表达式,循环继续执行。

对于这3种循环,任何中间的代码将被旁路。

class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}

该程序使用%(模)运算符来检验变量i是否为偶数,如果是,循环继续执行而不输出一个新行。该程序的结果如下:

0 1
2 3
4 5
6 7
8 9  

class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
System.out.println();
continue outer; }
System.out.print(" " + (i * j)); }}
System.out.println();
}

在本例中的continue 语句终止了计数j的循环而继续计数i的下一次循环反复。该程序的输出如下:

0
0 1
0 2 4
0 3 6 9
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81  

对于那些需要提早反复的特殊情形,continue 语句提供了一个结构化的方法来实现。

原文地址:https://www.cnblogs.com/xleer/p/5367260.html