在项目中遇到需要跳出内层for循环的同时,不执行外层for循环剩余语句,直接开始执行下一次外层for循环的问题。
我个人并不想使用变量来判断是否continue,最后发现可以通过为for循环命名,然后continue至特定的for循环来解决这个问题。
于是写个下面的例子记录一下。
获取第一个数组中第二个数组所没有的奇数,代码如下:
int[] one = {1, 4, 2, 8, 5, 7};
int[] two = {3, 0, 5, 6, 8, 9};
w:for (int i = 0; i < one.length; i++) {
if (one[i] % 2 == 1) {
for (int j = 0; j < two.length; j++) {
if (one[i] == two[j]) {
continue w;
}
}
System.out.println(one[i]);
}
}
这样就可以continue至指定的for循环,从而跳过外循环剩余的语句。