嵌套循环继续 java



我有以下循环:

for (int i = 0; i<arr.length;i++) {
for(int j =0; j<someArr.length; j++) {
//after this inner loop, continue with the other loop
}
}

我想打破内循环,继续外循环的迭代。我该怎么做?

通常你可以使用lablebreak的组合来跳转到你想要的位置,就像这样

OUTER_LOOP: for (int i = 0; i<arr.length;i++) {
for(int j =0; j<someArr.length; j++) {
//after this inner loop, continue with the other loop
break OUTER_LOOP;
}
}

如果你想像这样打破到外循环中的某个位置,请将标签放在要跳转到的位置(当前循环之外(,并在 break 语句中使用该标签

for (int i = 0; i<arr.length;i++) {
//line code 1
OUTER_LOOP: // line code 2
for(int j =0; j<someArr.length; j++) {
//after this inner loop, continue with the other loop
break OUTER_LOOP;
}
}
break

不会停止所有迭代。

因此,如果执行以下操作,则只会break嵌套循环(第二个for(之外,并继续第一个for循环的当前迭代:

for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < someArr.length; j++) {
break;
// NOT executed after the break instruction
}
// Executed after the break instruction
}

如果您将来需要它,您也可以使用continue语句。

Break将离开循环,但continue将跳过其余代码并跳转到下一个循环迭代。如果要跳过一些内部循环迭代,但继续执行相同的外循环迭代,这将非常有用。

这样:

for (int i = ... ) {
for (int y = ... ) {
if (some condition) {
continue;
}
// other code here to be executed if some condition is not met
}
}

你可以使用break

for (int i = 0; i<arr.length;i++) {
for(int j =0; j<someArr.length; j++) {
//after this inner loop, continue with the other loop
break;
}
// Executed after the break instruction
}

你必须在内部 for 循环中使用break;。 如果使用中断; 外部 for 循环将自动继续。您的代码将是:-

for (int i = 0; i<arr.length;i++) {
for(int j =0; j<someArr.length; j++) {
//after this inner loop, continue with the other loop
if(condition){
break; //break out of inner loop
}
}
}

最新更新