首页 > 解决方案 > 如何在for循环中跳出while循环

问题描述

我需要彻底摆脱 while 循环(空检查)并进入外部 for 循环的下一次迭代。

我试过把

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

如果产品日期不为空并且它执行 onething() 或 anotherthing() ,那么我想进入 for 循环的下一次迭代

标签: javafor-loopwhile-loop

解决方案


有几种方法。

您可以break从内部循环:

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

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

或者您可以标记外部循环,并continue与名称一起使用。默认情况下continuebreak应用于最内层循环,但使用名称会覆盖它。

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

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

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

有些人建议避免breakcontinue出于同样的原因,他们建议return在例行活动中避免。例程有多个退出点是让读者感到困惑的机会。

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


推荐阅读