如何在while循环中中断或继续嵌套的for循环



我可以在嵌套的for循环上使用break返回外部while循环,并从for循环内部使用continue强制while循环继续吗?我无法将for循环条件转换为while循环条件,因此如果我不能在特定满足的情况下继续,while循环可能会停止。

while(...some conditions...){
    ...print stuff
    for(...some instances are arrays, condition loop array...){
        if(...index meets conditions...){
            ...print once, some arrays might meet condition on multiple index
            break; //to prevent multiple printings
        }
    continue; //i don't want to force another while iteration if(false)
    //or is this continue for(loop) anyway?
    }
continue; //is this not essentially a while(true) loop with no return?
}

我之所以不能将for循环条件转换为while条件,是因为两个循环之间有更多的if条件,如if(array == null)和if条件x == true,如果数组没有传入,则需要调用getArray()。大多数时间条件yz都是从while循环打印的,但有时满足条件x,所以我需要for循环。是在打印for循环if(index true))之后,我需要while循环再次进行,我被卡住了吗?无论如何,在while循环条件下,有时可能会发生这种情况,但我可以看到它不会总是发生,更进一步,如果循环if(index false))满足,我不想强制执行while循环,因为这可能会在运行时处理中代价高昂,并可能导致无休止的循环。

PS我是一名初级程序员,我甚至不确定这是否可能?或者有道理,很抱歉,如果这是一个愚蠢的问题

您可以这样命名循环:

namedLoop: for(...) {
    // access your namedloop
    break namedLoop;
}

您可以使用带标签的break

下面是一个完整的例子:

https://docs.oracle.com/javase/tutorial/displayCode.html?code=https://docs.oracle.com/javase/tutorial/java/nutsandbolts/examples/BreakWithLabelDemo.java

基本上代码与此类似:

:myLabel

for (...) {
    for(...) {
        ...
        break myLabel; // Exit from both for loops
    }
}

continuebreak适用于当前的直接作用域,因此如果您在for内部,它将适用于for

您可以将比较结果存储在布尔变量上,以检查是否要continue

我不是breakcontinue的铁杆粉丝,在我看来,这妨碍了可读性。您可以使用不同的代码结构来实现相同的行为。

最新更新