[英]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. 我需要彻底打破while循环(空检查),然后转到外部for循环的下一个迭代。
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 如果产品日期不为null,并且执行onething()或anotherthing(),那么我想转到for循环的下一个迭代
There are a few ways. 有几种方法。
You can break
from the inner loop: 您可以
break
内循环:
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. 或者,您可以标记外循环,并使用
continue
名称。 By default continue
and break
apply to the innermost loop, but using a name overrides that. 默认情况下,
continue
和break
适用于最内部的循环,但是使用名称会覆盖该循环。
someName: for(...) {
while(...) {
...
if(condition) {
continue someName;
}
...
}
}
Or, you can usually achieve it without break
or continue
: 或者,您通常可以不
break
或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. 有些人建议避免
break
并出于相同的原因continue
工作,他们建议避免在例行中间return
。 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.