简体   繁体   English

在Java中,break如何与嵌套循环交互?

[英]In Java, how does break interact with nested loops?

我知道一个break语句跳出一个循环,但它是跳出嵌套循环还是只是它当前的循环?

Without any adornment, break will just break out of the innermost loop. 没有任何装饰, break将突破最内层的循环。 Thus in this code: 因此在这段代码中:

while (true) { // A
    while (true) { // B
         break;
    }
}

the break only exits loop B , so the code will loop forever. break仅退出循环B ,因此代码将永远循环。

However, Java has a feature called "named breaks" in which you can name your loops and then specify which one to break out of. 但是,Java有一个名为“命名中断”的功能,您可以在其中命名循环,然后指定要突破的循环。 For example: 例如:

A: while (true) {
    B: while (true) {
         break A;
    }
}

This code will not loop forever, because the break explicitly leaves loop A . 这段代码不会永远循环,因为break明确地留下了循环A

Fortunately, this same logic works for continue . 幸运的是,这个逻辑同样适用于continue By default, continue executes the next iteration of the innermost loop containing the continue statement, but it can also be used to jump to outer loop iterations as well by specifying a label of a loop to continue executing. 默认情况下, continue执行包含continue语句的最内层循环的下一次迭代,但也可以通过指定循环标签继续执行来跳转到外循环迭代。

In languages other than Java, for example, C and C++, this "labeled break" statement does not exist and it's not easy to break out of a multiply nested loop. 在Java以外的语言中,例如C和C ++,这种“标记中断”语句不存在,并且不容易打破多重嵌套循环。 It can be done using the goto statement, though this is usually frowned upon. 它可以使用goto语句完成,尽管这通常是不受欢迎的。 For example, here's what a nested break might look like in C, assuming you're willing to ignore Dijkstra's advice and use goto : 例如,假设您愿意忽略Dijkstra的建议并使用goto ,这里的嵌套中断可能在C中看起来像这样:

while (true) {
    while (true) {
        goto done;
    }
}
done:
   // Rest of the code here.

Hope this helps! 希望这可以帮助!

By default, it jumps out of the innermost loop. 默认情况下,它跳出最里面的循环。 But you can specify labels and make it jump of outer loops too. 但是你也可以指定标签并使其跳出外环

You can also break out by using Exceptions, so you can handle multiple reasons 您也可以使用例外来突破,这样您就可以处理多种原因

 void fkt1() {
    try {
        while (true)
            fkt2();
    } catch (YourAbortException e) {
        e.printStackTrace();
    }

    //go on
}

void fkt2() {
    while (true)
        if (abort)
            throw new YourAbortException();
}

it breaks 1 loop . 它打破了一个循环。 very simple. 非常简单。 for ex: 对于前:

for loop
   for loop
      break;
   end for loop
end for loop

break out of inner loop but still in outer loop 突破内循环,但仍然在外循环

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM