如何在for循环中突破while循环

时间:2019-05-16 09:57:12

标签: java for-loop while-loop

我需要彻底退出while循环(空检查)并转到外部for循环的下一个迭代。

我尝试放

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

如果产品日期不为null,并且执行onething()或anotherthing(),那么我想继续进行for循环的下一个迭代

2 个答案:

答案 0 :(得分:5)

有几种方法。

您可以从内部循环中break

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

这将离开内部循环,而外部循环将继续。

或者您可以标记外循环,并在名称上使用continue。默认情况下,continuebreak应用于最内层的循环,但是使用名称会覆盖该循环。

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

或者,您通常可以在没有breakcontinue的情况下实现它:

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

出于相同的原因,有些人建议避免使用breakcontinue,而在例行程序中则建议避免使用return。例行程序有多个退出点,这是使读者感到困惑的机会。

但是,可以通过确保例程简短来缓解这种情况。问题是您的出口点在长代码块中丢失了。

答案 1 :(得分:0)

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