Java continue语句
时间:2020-02-23 14:36:28 来源:igfitidea点击:
Java Continue语句用于跳过循环的当前迭代。
Java中的Continue语句可与for,while和do-while循环一起使用。
Java continue语句
在嵌套循环中使用continue语句时,它仅跳过内部循环的当前执行。
Java continue语句也可以与label一起使用,以跳过外部循环的当前迭代。
让我们看一些继续的Java语句示例。
Java 继续for循环
假设我们有一个整数数组,并且只想处理偶数,这里我们可以使用Continue循环跳过对奇数的处理。
package com.theitroad.java;
public class JavaContinueForLoop {
public static void main(String[] args) {
int[] intArray = { 1, 2, 3, 4, 5, 6, 7 };
//we want to process only even entries
for (int i : intArray) {
if (i % 2 != 0)
continue;
System.out.println("Processing entry " + i);
}
}
}
Java继续while循环
假设我们有一个数组,并且只想处理除以3的索引号。
我们可以在此处使用带有while循环的java continue语句。
package com.theitroad.java;
public class JavaContinueWhileLoop {
public static void main(String[] args) {
int[] intArray = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 };
int i = 0;
while (i < 10) {
if (i % 3 != 0) {
i++;
continue;
}
System.out.println("Processing Entry " + intArray[i]);
i++;
}
}
}
Java继续执行do-while循环
我们可以轻松地将上述while循环代码替换为do-while循环,如下所示。
Continue语句的结果和效果与上图相同。
do {
if (i % 3 != 0) {
i++;
continue;
}
System.out.println("Processing Entry " + intArray[i]);
i++;
} while (i < 10);
Java continue标签
让我们看一下Java继续标签示例,以跳过外循环处理。
在此示例中,我们将使用二维数组,并且仅当所有元素均为正数时才处理元素。
package com.theitroad.java;
import java.util.Arrays;
public class JavaContinueLabel {
public static void main(String[] args) {
int[][] intArr = { { 1, -2, 3 }, { 0, 3 }, { 1, 2, 5 }, { 9, 2, 5 } };
process: for (int i = 0; i < intArr.length; i++) {
boolean allPositive = true;
for (int j = 0; j < intArr[i].length; j++) {
if (intArr[i][j] < 0) {
allPositive = false;
continue process;
}
}
if (allPositive) {
//process the array
System.out.println("Processing the array of all positive ints. " + Arrays.toString(intArr[i]));
}
allPositive = true;
}
}
}
Java continue说明
关于Java Continue语句的一些重要要点是:
对于简单的情况,continue语句可以轻松地用if-else条件替换,但是当我们有多个if-else条件时,则使用continue语句会使我们的代码更具可读性。
在嵌套循环的情况下,continue语句很方便,并且可以跳过处理中的特定记录。

