java 有没有另一种方法可以在没有 break 语句的情况下退出循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33578543/
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-11-02 21:52:12  来源:igfitidea点击:

is there another way to exit a loop without a break statement

java

提问by joe smith

I am just curious as I have been using break statements a lot, but apparently I was told that is bad practice. Obviously logically if something is met it could terminate as well. I just want to know if there is something else besides break.

我只是很好奇,因为我经常使用 break 语句,但显然有人告诉我这是不好的做法。显然,如果满足某些事情,它也可以终止。我只是想知道除了break还有没有别的。

回答by sirmagid

That would break out of the for loop. In fact break only makes sense when talking about loops, since they break from the loop entirely, while continue only goes to the next iteration try this:

这将跳出 for 循环。事实上,break 只在谈论循环时才有意义,因为它们完全脱离循环,而 continue 只进入下一次迭代试试这个:

for(int i= 0; i<MAX; i++){
if(listEmpt[i] == null){
    listEmpt[i] = employeeObj;
    i=MAX;
}

but I see no problem with using breaks. There will always be circumstances where you want to stop processing a loop, and using a break; makes much more sense (and makes it more readable!) than setting your loop counter up to a value that would make your loop stop at the next iteration.

但我认为使用休息没有问题。在某些情况下,您希望停止处理循环并使用中断;比将循环计数器设置为使循环在下一次迭代中停止的值更有意义(并使其更具可读性!)。

you can also use labeled breaks that can break out of outer loops (and arbitrary code blocks)

您还可以使用可以跳出外部循环(和任意代码块)的标记中断

looplbl: for(int i=;i<;i++){

if (i == temp)
    // do something
else {
    temp = i;
    break looplbl;
}

}

}

An unlabelled break only breaks out of the enclosing switch, for, while or do-while construct. It does not take if statements into account.

未标记的中断仅从封闭的 switch、for、while 或 do-while 结构中跳出。它不考虑 if 语句。

See for more details.

有关更多详细信息,请参阅。

回答by Foleosy

With regards about the use of break, you could check here.

关于break的使用,可以查看这里。

Since while loops were not covered (another form of looping which I personally use a lot), you could look towards settings conditions for the loops such as

由于没有涵盖 while 循环(我个人经常使用的另一种循环形式),您可以查看循环的设置条件,例如

boolean flag = true;
while (flag) {
    //do something that modifies the below condition
    if (condition) {
        //do something
        flag = false;
    }
}

Upon which the loop will terminate when the condition equates to true, since that sets the flag to false.

当条件等于真时循环将终止,因为这将标志设置为假。

回答by cavalleydude

If you simply return from within your loop, that should be sufficient. Most people think you have to terminate the loop, but this is not the case.

如果您只是从循环中返回,那应该就足够了。大多数人认为您必须终止循环,但事实并非如此。

Also, see this answertoo.

另外,请参阅此答案