简体   繁体   English

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

[英]What is the “continue” keyword and how does it work in Java?

I saw this keyword for the first time and I was wondering if someone could explain to me what it does.我第一次看到这个关键字,我想知道是否有人可以向我解释它的作用。

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

continue is kind of like goto . continue有点像goto Are you familiar with break ?你熟悉break吗? It's easier to think about them in contrast:相比之下,更容易考虑它们:

  • break terminates the loop (jumps to the code below it). break终止循环(跳转到它下面的代码)。

  • continue terminates the rest of the processing of the code within the loop for the current iteration, but continues the loop. continue终止循环中当前迭代的其余代码处理,但继续循环。

A continue statement without a label will re-execute from the condition the innermost while or do loop, and from the update expression of the innermost for loop.没有标签的continue语句将从最里面的whiledo循环的条件和最里面的for循环的更新表达式重新执行。 It is often used to early-terminate a loop's processing and thereby avoid deeply-nested if statements.它通常用于提前终止循环的处理,从而避免深度嵌套的if语句。 In the following example continue will get the next line, without processing the following statement in the loop.在下面的示例中, continue将获取下一行,而不处理循环中的以下语句。

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

With a label, continue will re-execute from the loop with the corresponding label, rather than the innermost loop.带有标签, continue将从带有相应标签的循环重新执行,而不是从最里面的循环开始。 This can be used to escape deeply-nested loops, or simply for clarity.这可以用来逃避深层嵌套的循环,或者只是为了清楚起见。

Sometimes continue is 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++.没有标签的相同语句也存在于 C 和 C++ 中。 The equivalent in Perl is next . Perl 中的等价物是next

This type of control flow is not recommended, but if you so choose you can also use continue to simulate a limited form of goto .不推荐使用这种类型的控制流,但如果您选择这样做,您也可以使用continue来模拟有限形式的goto In the following example the continue will re-execute the empty for (;;) loop.在以下示例中, continue将重新执行空的for (;;)循环。

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

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 的奇数的总和。

If you think of the body of a loop as a subroutine, continue is sort of like return .如果您将循环体视为子例程,那么continue有点像return The same keyword exists in C, and serves the same purpose.相同的关键字存在于 C 中,用于相同的目的。 Here's a contrived example:这是一个人为的例子:

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

This will print out only the odd numbers.这将仅打印出奇数。

Generally, I see continue (and break ) as a warning that the code might use some refactoring, especially if the while or for loop declaration isn't immediately in sight.通常,我将continue (和break )视为代码可能使用一些重构的警告,尤其是在whilefor循环声明不是立即可见的情况下。 The same is true for return in the middle of a method, but for a slightly different reason.方法中间的return也是如此,但原因略有不同。

As others have already said, continue moves along to the next iteration of the loop, while break moves out of the enclosing loop.正如其他人已经说过的, continue移动到循环的下一次迭代,而break移出封闭循环。

These can be maintenance timebombs because there is no immediate link between the continue / break and the loop it is continuing/breaking other than context;这些可能是维护定时炸弹,因为除了上下文之外,在continue / break和它正在continue / break的循环之间没有直接联系; add an inner loop or move the "guts" of the loop into a separate method and you have a hidden effect of the continue / break failing.添加一个内部循环或将循环的“胆量”移动到一个单独的方法中,并且您对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". continuebreakreturn (方法末尾的 One True Return 除外)都属于“隐藏 GOTO”的一般类别。 They place loop and function control in unexpected places, which then eventually causes bugs.他们将循环和函数控制放在意想不到的地方,这最终会导致错误。

"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+"");
}

As already mentioned continue will skip processing the code below it and until the end of the loop.正如已经提到的, continue将跳过处理它下面的代码,直到循环结束。 Then, you are moved to the loop's condition and run the next iteration if this condition still holds (or if there is a flag, to the denoted loop's condition).然后,你将移动到循环的条件和运行下一次迭代如果这种情况仍持有(或有一个标志,在表示为循环的条件)。

It must be highlighted that in the case of do - while you are moved to the condition at the bottom after a continue , not at the beginning of the loop.必须强调的是,在do - while的情况下,您将在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 aSet will contain odd numbers only 100%... you are wrong! *如果你的答案是aSet只包含 100% 的奇数......你错了!

Continue is a keyword in Java & it is used to skip the current iteration. Continue是 Java 中的一个关键字,用于跳过当前迭代。

Suppose you want to print all odd numbers from 1 to 100假设你想打印从 1 到 100 的所有奇数

public class Main {

    public static void main(String args[]) {

    //Program to print all odd numbers from 1 to 100

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

    }
}

continue statement in the above program simply skips the iteration when i is even and prints the value of i when it is odd.上述程序中的continue语句仅在i为偶数时跳过迭代,并在i为奇数时打印i的值。

Continue statement simply takes you out of the loop without executing the remaining statements inside the loop and triggers the next iteration. Continue语句只是将您带出循环,而不执行循环内的其余语句并触发下一次迭代。

Consider an If Else condition.考虑 If Else 条件。 A continue statement executes what is there in a condition and gets out of the condition ie jumps to next iteration or condition. continue 语句执行条件中的内容并退出条件,即跳转到下一次迭代或条件。 But a Break leaves the loop.但是 Break 离开了循环。 Consider the following Program.考虑以下程序。 ' '

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 ie "cc".equals(ss).如果满足条件“bb”等于 ss: For Continue:它进入下一次迭代,即“cc”.equals(ss)。 For Break: It comes out of the loop and prints "Out of the loop. "对于 Break:它退出循环并打印“退出循环”。

I'm a bit late to the party, but...我参加聚会有点晚了,但是...

It's worth mentioning that continue is useful for empty loops where all of the work is done in the conditional expression controlling the loop.值得一提的是, continue对于所有工作都在控制循环的条件表达式中完成的空循环很有用。 For example:例如:

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

In this case, all of the work of reading a character and appending it to buffer is done in the expression controlling the while loop.在这种情况下,读取字符并将其附加到buffer的所有工作都在控制while循环的表达式中完成。 The continue statement serves as a visual indicator that the loop does not need a body. 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 (...)
    ;

Basically in java, continue is a statement.基本上在java中, continue 是一个语句。 continue statement jumps to next iteration of a loop based on specific condition. continue 语句根据特定条件跳转到循环的下一次迭代。

continue statement is normally used with the loops to skip the current iteration. continue 语句通常与循环一起使用以跳过当前迭代。 For how and when it is used in java, refer link below.有关在 Java 中使用它的方式和时间,请参阅下面的链接。

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

Hope it helps !!希望有帮助!!

The continue statement is used in loop control structure when you need to jump to the next iteration of the loop immediately.当您需要立即跳转到循环的下一次迭代时,在循环控制结构中使用 continue 语句。

It can be used with for loop or while loop.它可以与 for 循环或 while 循环一起使用。 The Java continue statement is used to continue the loop. Java continue 语句用于继续循环。 It continues the current flow of the program and skips the remaining code at the specified condition.它继续程序的当前流程,并在指定条件下跳过剩余的代码。

In case of an inner loop, it continues the inner loop only.在内部循环的情况下,它仅继续内部循环。

We can use Java continue statement in all types of loops such as for loop, while loop and do-while loop.我们可以在所有类型的循环中使用 Java continue 语句,例如 for 循环、while 循环和 do-while 循环。

for example例如

class Example{
    public static void main(String args[]){
        System.out.println("Start");
        for(int i=0; i<10; i++){
            if(i==5){continue;}
            System.out.println("i : "+i);   
        }
        System.out.println("End.");
    }
}

output:输出:

Start
i : 0
i : 1
i : 2
i : 3
i : 4
i : 6
i : 7
i : 8
i : 9
End.

[number 5 is skip] [数字5是跳过]

continue must be inside a loop Otherwise it showsThe error below: continue必须在循环内,否则会显示以下错误:

Continue outside the loop在循环外继续

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

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