-->

What is the “continue” keyword and how does it wor

2018-12-31 16:32发布

问题:

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?
  • How does it work?
  • When is it used?

回答1:

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. It is often used to early-terminate a loop\'s processing and thereby avoid deeply-nested if statements. In the following example continue will get the next line, without processing the following statement in the loop.

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. 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.

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.

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. In the following example the continue will re-execute the empty for (;;) loop.

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


回答2:

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

  • break terminates the loop (jumps to the code below it).

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



回答3:

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.



回答4:

If you think of the body of a loop as a subroutine, continue is sort of like return. The same keyword exists in C, and serves the same purpose. 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.



回答5:

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. The same is true for return in the middle of a method, but for a slightly different reason.

As others have already said, continue moves along to the next iteration of the loop, while break moves out of the enclosing loop.

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; 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.

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.



回答6:

As already mentioned continue will skip processing the code below it and until the end of the loop. 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.

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!



回答7:

\"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

Example: This is a code to print the odd numbers from 1 to 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+\"\");
}



回答8:

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. \'

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.

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

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. \"



回答9:

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. 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. The continue statement serves as a visual indicator that the loop does not need a body.

It\'s a little more obvious than the equivalent:

while (...)
{ }

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

while (...)
    ;


回答10:

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

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

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

Hope it helps !!