java 带中断的循环迭代器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1789164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 17:58:56  来源:igfitidea点击:

iterator for loops with break

java

提问by cometta

let say my code look like below

假设我的代码如下所示

for(..)
  for(..)
    for(..){
            break;  //this will break out from the most inner loop OR all 3 iterated loops?
    }

回答by Greg Hewgill

Your example will break out of the innermost loop only. However, using a labeled breakstatement, you can do this:

您的示例只会跳出最内层的循环。但是,使用带标签的 break语句,您可以执行以下操作:

outer:
  for(..)
    for(..)
      for(..){
        break outer;  //this will break out from all three loops
      }

回答by Otto Allmendinger

This will only break out from the inner loop. You can also define a scope to break out from. More from the language specs:

这只会从内部循环中跳出。您还可以定义一个范围来突破。更多来自语言规范

A break statement with no label attempts to transfer control to the innermost enclosing switch, while, do, or for statement of the immediately enclosing method or initializer block; this statement, which is called the break target, then immediately completes normally.

没有标签的 break 语句试图将控制转移到最里面的封闭开关、while、do 或 for 立即封闭方法或初始化程序块的语句;此语句称为中断目标,然后立即正常完成。

回答by AttishOculus

Think a bit about these questions, maybe this way you'll learn more than alone from getting the answer (which has already been posted by now, I'm sure):

想一想这些问题,也许这样你会从得到答案中学到更多(我敢肯定,现在已经发布了):

  • if you were alone, how would you decide? Make up a test case where it gets evident.
  • if you were to invent a language and add a break construct, how would it work? Which one would be the more useful behavior? Which one would be the one most people expected?
  • how would you solve breaking out of nested for loops in Java? In C or C++? In a language with no labels of any kind?
  • 如果你一个人,你会如何决定?组成一个测试用例,它变得明显。
  • 如果你要发明一种语言并添加一个中断结构,它会如何工作?哪一个是更有用的行为?哪一个是大多数人期望的?
  • 您将如何解决 Java 中嵌套 for 循环的中断问题?在 C 或 C++ 中?用一种没有任何标签的语言?

You'd be surprised at how much you can learn from these simple self-made exercises.

你会惊讶于你可以从这些简单的自制练习中学到多少东西。

回答by TimW

Yes, without labels it will break only the most inner loop.
Instead of using labels you can put your loops in a seperated function and return from the function.

是的,如果没有标签,它只会破坏最内部的循环。
您可以将循环放在一个单独的函数中并从该函数返回,而不是使用标签。

class Loop {
    public void loopForXx() {
        untilXx();
    }

    private void untilXx() {
        for()
            for()
                for()
                    if(xx)
                        return; 
    }
}

回答by Toms

From the most inner loop :)

从最内层循环:)

    int i,j,k;
    for(i = 0; i < 2; i++)
            for(j = 0; j < 2; j++)
                    for(k = 0; k < 2; k++)
                    {
                            printf("%d %d %d\n", i, j, k);
                            break;
                    }

Will produce :

将产生:

0 0 0
0 1 0
1 0 0
1 1 0

回答by Dimitri

as often mentioned i don't like to break with a label eather. so while in a for loop most of the time i'm adding a boolean varible to simple exit the loop.. (only if i want to break it of cause;))

正如经常提到的,我不喜欢打破标签eather。所以在 for 循环中的大部分时间我都添加了一个布尔变量来简单地退出循环..(只有当我想打破它的原因时;))

boolean exit = false;
for (int i = 0; i < 10 && !exit; i++) {
   for (int j = 0; j < 10 && !exit; j++) {
      exit = true;
   }
}

this is in my opinion more elegant than a break..

在我看来,这比休息更优雅..

回答by Adriaan Koster

Many people here don't like labels and breaking. This technique can be compared to using a 'goto' statement, a flow control statement which allows jumping out of a block of code in a non-standard way, obliviating use of pre- and post conditions. Edsger Dijkstra published a famous article in Communications of the ACM, march 1968, 'Goto statement considered harmful' (it's a short read).

这里的许多人不喜欢标签和破坏。这种技术可以与使用“goto”语句进行比较,这是一种流控制语句,允许以非标准方式跳出代码块,无需使用前置条件和后置条件。Edsger Dijkstra 在 1968 年 3 月的 ACM 通讯中发表了一篇著名的文章,“Goto 语句被认为是有害的”(这是一个简短的阅读)。

Using the same reasoning presented in the article, returning from inside an iteration as suggested by TimW is also bad practice. If one is strict, to create readable code, with predictable entry- and exit points, one should initialize the variable which will hold the return value (if any) at the beginning of the method and return only at the end of a mehod.

使用本文中提出的相同推理,从 TimW 建议的迭代内部返回也是不好的做法。如果是严格的,要创建具有可预测入口和出口点的可读代码,则应初始化将在方法开始时保存返回值(如果有)并仅在方法结束时返回的变量。

This poses a challenge when using an iteration to perform a lookup. To avoid using break or return one inevitably ends up with a while-loop with a regular stop condition and some boolean variable to indicate that the lookup has succeeded:

这在使用迭代执行查找时带来了挑战。为了避免使用 break 或 return ,不可避免地会以带有常规停止条件和一些布尔变量的 while 循环结束,以指示查找已成功:

boolean targetFound = false;
int i = 0;
while (i < values.size() && ! targetFound ) {

    if (values.get(i).equals(targetValue)) {   
        targetFound  = true;
    }
}
if (!targetFound) {
    // handle lookup failure
} 

Ok, this works, but it seems a bit clunky to me. First of all I have to introduce a boolean to detect lookup success. Secondly I have to explicitly check targetFound after the loop to handle lookup failure.

好的,这有效,但对我来说似乎有点笨拙。首先,我必须引入一个布尔值来检测查找是否成功。其次,我必须在循环后显式检查 targetFound 以处理查找失败。

I sometimes use this solution, which I think is more concise and readable:

我有时会使用这个解决方案,我认为它更简洁易读:

lookup: {

    for(Value value : values) {

        if (value.equals(targetValue)) {   
            break lookup;  
        }
    }
    // handle lookup failure here
}

I think breaking (no pun intended) the rule here results in better code.

我认为打破(没有双关语)这里的规则会导致更好的代码。

回答by ufukgun

it will breake from most inner loop,

它会从大多数内部循环中断,

if you want to break from all, you can hold a variable and change its value when you want to break, then control it at the beginning of each for loop

如果你想从所有的中断,你可以持有一个变量,当你想中断的时候改变它的值,然后在每个for循环的开始控制它