在 Java 中退出循环

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

Exiting a loop in Java

javacoding-style

提问by null0pointer

I'm using Java but I guess this question applies to whatever language. I just want to ask whether it's better practice to exit a loop using a boolean which I toggle within the loop or to just use break;

我正在使用 Java,但我想这个问题适用于任何语言。我只是想问一下使用我在循环内切换的布尔值退出循环还是只使用 break 是否更好;

For example, I was just writing a method to get the valid moves for a Queen in chess.

例如,我只是在编写一种方法来获取国际象棋皇后的有效走法。

private static final int[][] DIRS = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {-1, -1}, {-1, 1}, {1, -1}};

public Vector<Move> getValidMoves() {
    Vector<Move> validMoves = new Vector<Move>();

    for (int i = 0; i < DIRS.length; i++) {
        boolean stopped = false;
        int newX = x + DIRS[i][0];
        int newY = y + DIRS[i][1];
        while (!stopped && newX >= 0 && newX < 8 && newY >= 0 && newY < 8) {
            if (board[newX][newY] == null) {
                validMoves.add(new Move(x, y, newX, newY));
                newX += DIRS[i][0];
                newY += DIRS[i][1];
            } else {
                if (board[newX][newY].getColour() == colour) {
                    stopped = true;
                } else {
                    validMoves.add(new Move(x, y, newX, newY));
                    stopped = true;
                }
            }
        }
    }

    return validMoves;
}

If I exit the while loop using break; instead of setting stopped to true like I do it's my understanding that it runs more efficiently but is not the greatest code style.

如果我使用 break 退出 while 循环;而不是像我那样将停止设置为真,我的理解是它运行更有效,但不是最好的代码风格。

回答by Johan Sj?berg

breakexists for the sole reason of exiting a loop, I can't think of any better way to do that.

break存在的唯一原因是退出循环,我想不出任何更好的方法来做到这一点。

回答by Vincent Mimoun-Prat

Performance-wise, it won't matter much, you are allocating 1 boolean on the stack and adding 1 comparison at each loop iteration, so nothing to worry about.

在性能方面,它不会有太大影响,您在堆栈上分配 1 个布尔值并在每次循环迭代时添加 1 个比较,因此无需担心。

It mainly depends on whether you want to finish executing the rest of the loop code before exiting it or not. Break will exit immediatly and setting a boolean will wait for the next iteration before stopping.

这主要取决于您是否要在退出之前完成其余循环代码的执行。Break 将立即退出并设置一个布尔值将在停止之前等待下一次迭代。

If you don't need to finish the loop iteration, your code will be easier to read if you use break

如果你不需要完成循环迭代,你的代码会更容易阅读,如果你使用 break

回答by katsuya

As using boolean variable here does not affect much for performance, this is about readability. Some people believes using break statement reduces code's readability for two reasons.

由于在这里使用布尔变量对性能影响不大,这是关于可读性的。有些人认为使用 break 语句会降低代码的可读性,原因有两个。

One is that user sometimes cannot read the code sequentially (need to jump read) when break statement is used. This can be confusing as reader need to determine where the break statement brings next operation to.

一是用户在使用break语句时,有时无法顺序阅读代码(需要跳转阅读)。这可能会令人困惑,因为读者需要确定 break 语句将下一个操作带到哪里。

Another thing is that using variable for stop condition helps reader understands why it is stopped if you name the variable meaningfully. e.g if you use isEmpty boolean variable for stop condition, it is very clear that the loop has stopped because whatever is empty.

另一件事是,如果您有意义地命名变量,则使用变量作为停止条件可以帮助读者理解为什么停止。例如,如果你使用 isEmpty 布尔变量作为停止条件,很明显循环已经停止,因为无论什么都是空的。

I am not against using break statement but I think what you should do is to make it readable as possible.

我不反对使用 break 语句,但我认为您应该做的是使其尽可能具有可读性。

回答by Jason Rogers

You may want to read up on the usage of break from the oracle webpage

您可能想从 oracle 网页上阅读 break 的用法

Branching Statements Tutorial

分支语句教程

using a Break to exit a loop is accept as a good practice. then if you use it or not is up to you.

使用 Break 退出循环是一种很好的做法。那么你是否使用它取决于你。

now if you want to improve the readability of your code and its flexibility you can consider breaking down you complex loops into functions.

现在,如果您想提高代码的可读性及其灵活性,您可以考虑将复杂的循环分解为函数。

回答by Peter Lawrey

I suggest you do what you believe is clearest. IMHO Using a boolean can be clearer for nested loops, but for simple loops using a flag is needlessly verbose.

我建议你做你认为最清楚的事情。恕我直言,对于嵌套循环,使用布尔值可以更清晰,但对于使用标志的简单循环,则不必要地冗长。

while (0 <= newX && newX < 8 && 0 <= newY && newY < 8) {
    if (board[newX][newY] == null) {
        validMoves.add(new Move(x, y, newX, newY));
        newX += DIRS[i][0];
        newY += DIRS[i][1];
    } else {
        if (board[newX][newY].getColour() != colour) 
            validMoves.add(new Move(x, y, newX, newY));
        break;
    }
}

回答by Damon

Definitively use break. That is what the keyword is for, it generates more concise code, does not make someone reading your code wonder where that "stopped" in the loop comes from, and is likely faster, too.

绝对使用break。这就是关键字的用途,它生成更简洁的代码,不会让阅读您的代码的人想知道循环中的“停止”来自哪里,并且速度也可能更快。

回答by Chris Aldrich

Depends on who you talk to. I have a college professor who swore he'd shoot any student who didn't exit a control structure (such as a loop) with a normal expression check.

取决于你和谁说话。我有一位大学教授发誓他会射杀任何没有通过正常表达式检查退出控制结构(例如循环)的学生。

However, I have seen that as much as that might be "disciplined", there are times where to exit a loop or other control structure early is desireable. With that in mind, I say "go for it". You can still be disciplined and have readable code that does not have unexpected behavior with an early exit (as long as that exit would be a valid reason for leaving that structure.

但是,我已经看到,尽管这可能是“纪律严明的”,但有时需要尽早退出循环或其他控制结构。考虑到这一点,我说“去吧”。您仍然可以遵守纪律,并拥有在提前退出时不会出现意外行为的可读代码(只要该退出是离开该结构的正当理由。

回答by CloudyMarble

Thats exactly why there is breakin the language. I would just use it.

这正是语言中断的原因。我只会用它。

回答by Koh Jing Yu

Like the users above mentioned, definitely use break. Exiting loops is what it's made for.

像上面提到的用户一样,一定要使用break。退出循环就是它的目的。

回答by davin

A point that seems not to have been raised yet:

一个似乎还没有被提出的观点:

In Java (not exclusively though), exiting nested loops will be moreelegant with breakthan having the same condition nested in every level. It will also make the code more maintainable.

在 Java 中(虽然不是唯一的),退出嵌套循环将比在每个级别嵌套相同的条件优雅break。它还将使代码更易于维护。

In addition, it can make the logic of the loop much more simple, because as soon as your come to a breaking condition you can act, rather than continue executing code. This too promotoes modularity within the loop body.

此外,它可以使循环的逻辑更加简单,因为一旦遇到中断条件,您就可以采取行动,而不是继续执行代码。这也促进了循环体内的模块化。