简体   繁体   中英

How to break out of while loop within for loop

I need to cleanly break out of a while loop(null check) and go to the next iteration of the outer for loop.

I have tried putting

for(Product: product:ListofProducts){
 while(null!=product.getDate){
    if(product.getDate>specifiedDate){
        doOnething()
    }
    else{
        doAnotherThing()
    }
    continue;
}

if the product date is not null and it does onething() or anotherthing() , then I want to move onto the next iteration of the for loop

There are a few ways.

You can break from the inner loop:

for(...) {
    while(...) {
       ... 
       if(condition) {
          break;
       }
       ...
    }
 }

This will leave the inner loop and the outer loop will continue.

Or you can label the outer loop, and use continue with the name. By default continue and break apply to the innermost loop, but using a name overrides that.

someName: for(...) {
    while(...) {
       ... 
       if(condition) {
          continue someName;
       }
       ...
    }
 }

Or, you can usually achieve it without break or continue :

for(...) {
    boolean done = false;
    while(... && !done) {
       ... 
       if(condition) {
          done = true;
       }
    }
 }

Some people advise avoiding break and continue for the same reason they advise avoiding return in the middle of a routine. Having more than one exit point for a routine is an opportunity for confusing the reader.

However, that can be mitigated by ensuring the routine is short. The problem is where your exit points get lost in long blocks of code.

for(Product: product:ListofProducts){
 boolean done = false;
 while(null!=product.getDate && !done){
    if(product.getDate>specifiedDate){
        doOnething();
        done = true;
    }
    else{
        doAnotherThing();
        done = true;
    }
    continue;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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