什么是“continue”关键字?它在 Java 中是如何工作的?

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

What is the "continue" keyword and how does it work in Java?

javakeywordcontinue

提问by faceless1_14

I saw this keyword for the first time and I was wondering if someone could explain to me what it does.

我第一次看到这个关键字,我想知道是否有人可以向我解释它的作用。

  • What is the continuekeyword?
  • How does it work?
  • When is it used?
  • continue关键字是什么?
  • 它是如何工作的?
  • 什么时候使用?

采纳答案by Diomidis Spinellis

A continuestatement without a label will re-execute from the condition the innermost whileor doloop, and from the update expression of the innermost forloop. It is often used to early-terminate a loop's processing and thereby avoid deeply-nested ifstatements. In the following example continuewill get the next line, without processing the following statement in the loop.

continue没有标签的语句将根据最内层whiledo循环的条件和最内层循环的更新表达式重新执行for。它通常用于提前终止循环的处理,从而避免深度嵌套的if语句。在下面的例子continue中将得到下一行,不处理循环中的以下语句。

while (getNext(line)) {
  if (line.isEmpty() || line.isComment())
    continue;
  // More code here
}

With a label, continuewill re-execute from the loop with the corresponding label, rather than the innermost loop. This can be used to escape deeply-nested loops, or simply for clarity.

带有标签,continue会从带有相应标签的循环中重新执行,而不是最里面的循环。这可以用来逃避深层嵌套的循环,或者只是为了清楚起见。

Sometimes continueis also used as a placeholder in order to make an empty loop body more clear.

有时continue也用作占位符以使空循环体更清晰。

for (count = 0; foo.moreData(); count++)
  continue;

The same statement without a label also exists in C and C++. The equivalent in Perl is next.

没有标签的相同语句也存在于 C 和 C++ 中。Perl 中的等价物是next.

This type of control flow is not recommended, but if you so choose you can also use continueto simulate a limited form of goto. In the following example the continuewill re-execute the empty for (;;)loop.

不推荐使用这种类型的控制流,但如果您选择了,您也可以使用它continue来模拟有限形式的goto. 在以下示例中,continue将重新执行空for (;;)循环。

aLoopName: for (;;) {
  // ...
  while (someCondition)
  // ...
    if (otherCondition)
      continue aLoopName;

回答by Dustin

continueis kind of like goto. Are you familiar with break? It's easier to think about them in contrast:

continue有点像goto。你熟悉break吗?相比之下,更容易考虑它们:

  • breakterminates the loop (jumps to the code below it).

  • continueterminates the rest of the processing of the code within the loop for the current iteration, but continues the loop.

  • break终止循环(跳转到它下面的代码)。

  • continue终止循环内当前迭代的其余代码处理,但继续循环。

回答by Gant

Let's see an example:

让我们看一个例子:

int sum = 0;
for(int i = 1; i <= 100 ; i++){
    if(i % 2 == 0)
         continue;
    sum += i;
}

This would get the sum of only odd numbers from 1 to 100.

这将只得到从 1 到 100 的奇数的总和。

回答by Vineet

If you think of the body of a loop as a subroutine, continueis sort of like return. The same keyword exists in C, and serves the same purpose. Here's a contrived example:

如果您将循环体视为子例程,continue则有点像return. 相同的关键字存在于 C 中,用于相同的目的。这是一个人为的例子:

for(int i=0; i < 10; ++i) {
  if (i % 2 == 0) {
    continue;
  }
  System.out.println(i);
}

This will print out only the odd numbers.

这将仅打印出奇数。

回答by Tom Dibble

Generally, I see continue(and break) as a warning that the code mightuse some refactoring, especially if the whileor forloop declaration isn't immediately in sight. The same is true for returnin the middle of a method, but for a slightly different reason.

通常,我将continue(和break) 视为代码可能使用一些重构的警告,尤其是在whileorfor循环声明不是立即可见的情况下。return方法中间也是如此,但原因略有不同。

As others have already said, continuemoves along to the next iteration of the loop, while breakmoves out of the enclosing loop.

正如其他人已经说过的那样,continue移动到循环的下一次迭代,同时break移出封闭循环。

These can be maintenance timebombs because there is no immediate link between the continue/breakand the loop it is continuing/breaking other than context; add an inner loop or move the "guts" of the loop into a separate method and you have a hidden effect of the continue/breakfailing.

这些可能是维护定时炸弹,因为除了上下文之外,continue/break和它正在继续/中断的循环之间没有直接联系;添加一个内部循环或将循环的“胆量”移动到一个单独的方法中,并且您具有continue/break失败的隐藏效果。

IMHO, it's best to use them as a measure of last resort, and then to make sure their use is grouped together tightly at the start or end of the loop so that the next developer can see the "bounds" of the loop in one screen.

恕我直言,最好将它们用作最后​​手段,然后确保它们的使用在循环的开始或结束时紧密组合在一起,以便下一个开发人员可以在一个屏幕中看到循环的“边界” .

continue, break, and return(other than the One True Return at the end of your method) all fall into the general category of "hidden GOTOs". They place loop and function control in unexpected places, which then eventually causes bugs.

continuebreak、 和return(方法末尾的 One True Return 除外)都属于“隐藏 GOTO”的一般类别。他们将循环和函数控制放在意想不到的地方,这最终会导致错误。

回答by Kostas Chalkias

As already mentioned continuewill skip processing the code below it and until the end of the loop. Then, you are moved to the loop's conditionand run the next iteration if this condition still holds (or if there is a flag, to the denoted loop's condition).

如前所述,continue将跳过处理它下面的代码,直到循环结束。然后,你将移动到循环的条件和运行下一次迭代如果这种情况仍持有(或有一个标志,在表示为循环的条件)。

It must be highlighted that in the case of do - whileyou are moved to the condition at the bottom after a continue, not at the beginning of the loop.

必须强调的是,如果do - while您在 a 之后移动到底部的条件continue,而不是在循环的开头。

This is why a lot of people fail to correctly answer what the following code will generate.

这就是为什么很多人无法正确回答以下代码将生成什么的原因。

    Random r = new Random();
    Set<Integer> aSet= new HashSet<Integer>();
    int anInt;
    do {
        anInt = r.nextInt(10);
        if (anInt % 2 == 0)
            continue;
        System.out.println(anInt);
    } while (aSet.add(anInt));
    System.out.println(aSet);

*If your answer is that aSetwill contain odd numbers only 100%... you are wrong!

*如果您的答案是aSet仅 100% 包含奇数……那您就错了!

回答by phanindravarma

Consider an If Else condition. A continue statement executes what is there in a condition and gets out of the condition i.e. jumps to next iteration or condition. But a Break leaves the loop. Consider the following Program. '

考虑 If Else 条件。continue 语句执行条件中的内容并退出条件,即跳转到下一次迭代或条件。但是 Break 离开了循环。考虑以下程序。'

public class ContinueBreak {
    public static void main(String[] args) {
        String[] table={"aa","bb","cc","dd"};
        for(String ss:table){
            if("bb".equals(ss)){
                continue;
            }
            System.out.println(ss);
            if("cc".equals(ss)){
                break;
            }
        }
        System.out.println("Out of the loop.");
    }

}

It will print: aa cc Out of the loop.

它将打印: aa cc Out of the loop。

If you use break in place of continue(After if.), it will just print aa and out of the loop.

如果您使用 break 代替 continue(After if.),它只会打印 aa 并退出循环

If the condition "bb" equals ss is satisfied: For Continue: It goes to next iteration i.e. "cc".equals(ss). For Break: It comes out of the loop and prints "Out of the loop. "

如果满足条件“bb”等于 ss: For Continue:它进入下一次迭代,即“cc”.equals(ss)。对于 Break:它退出循环并打印“退出循环”。

回答by Shiva

Basically in java, continue is a statement. So continue statement is normally used with the loops to skip the current iteration.

基本上在java中, continue 是一个语句。因此 continue 语句通常与循环一起使用以跳过当前迭代。

For how and when it is used in java, refer link below. It has got explanation with example.

有关在 Java 中使用它的方式和时间,请参阅下面的链接。它有例子的解释。

https://www.flowerbrackets.com/continue-java-example/

https://www.flowerbrackets.com/continue-java-example/

Hope it helps !!

希望能帮助到你 !!

回答by Ibrahim Hout

"continue" in Java means go to end of the current loop, means: if the compiler sees continue in a loop it will go to the next iteration

Java 中的“continue”表示跳到当前循环的结尾,意思是:如果编译器看到continue in a loop,它将进入下一次迭代

Example: This is a code to print the odd numbers from 1 to 10

示例:这是一个打印从 1 到 10 的奇数的代码

the compiler will ignore the print code whenever it sees continue moving into the next iteration

每当编译器看到继续进入下一次迭代时,它就会忽略打印代码

for (int i = 0; i < 10; i++) { 
    if (i%2 == 0) continue;    
    System.out.println(i+"");
}


回答by David R Tribble

I'm a bit late to the party, but...

我参加聚会有点晚了,但是...

It's worth mentioning that continueis useful for empty loops where all of the work is done in the conditional expression controlling the loop. For example:

值得一提的continue是,这对于所有工作都在控制循环的条件表达式中完成的空循环很有用。例如:

while ((buffer[i++] = readChar()) >= 0)
    continue;

In this case, all of the work of reading a character and appending it to bufferis done in the expression controlling the whileloop. The continuestatement serves as a visual indicator that the loop does not need a body.

在这种情况下,读取字符并将其附加到buffer的所有工作都在控制while循环的表达式中完成。该continue语句用作循环不需要主体的视觉指示符。

It's a little more obvious than the equivalent:

它比等价物更明显一点:

while (...)
{ }

and definitely better (and safer) coding style than using an empty statement like:

并且绝对比使用空语句更好(更安全)的编码风格,例如:

while (...)
    ;