java - 如何在for循环中跳出while循环
问题描述
我需要彻底摆脱 while 循环(空检查)并进入外部 for 循环的下一次迭代。
我试过把
for(Product: product:ListofProducts){
while(null!=product.getDate){
if(product.getDate>specifiedDate){
doOnething()
}
else{
doAnotherThing()
}
continue;
}
如果产品日期不为空并且它执行 onething() 或 anotherthing() ,那么我想进入 for 循环的下一次迭代
解决方案
有几种方法。
您可以break
从内部循环:
for(...) {
while(...) {
...
if(condition) {
break;
}
...
}
}
这将离开内循环,外循环将继续。
或者您可以标记外部循环,并continue
与名称一起使用。默认情况下continue
并break
应用于最内层循环,但使用名称会覆盖它。
someName: for(...) {
while(...) {
...
if(condition) {
continue someName;
}
...
}
}
或者,您通常可以在没有break
or的情况下实现它continue
:
for(...) {
boolean done = false;
while(... && !done) {
...
if(condition) {
done = true;
}
}
}
有些人建议避免break
,continue
出于同样的原因,他们建议return
在例行活动中避免。例程有多个退出点是让读者感到困惑的机会。
但是,可以通过确保例程简短来缓解这种情况。问题是您的退出点在长代码块中丢失。
推荐阅读
- hl7 - 所有 HL7 段结构表头是什么意思?
- java - 如何在 JAVA 中获取 Windows 10 Build 版本
- google-chrome - 从多个 url 保存 html 代码
- android - 我的广播接收器是显式的还是隐式的?
- ffmpeg - ffmpeg 初始化输出流时出错 0:0 -- 打开输出流编码器时出错
- spring - Spring MVC 中的控制器不共享 Cookie
- javascript - Firebase numChildren() 在本机反应中始终返回 0
- hadoop - Hadoop namenode 不以退出代码 1 开头
- python - 附加到具有性能的 tar 文件
- python - SQLAlchemy ResultProxy 按需加载行?