定期循环
for (int i = 0; i < 10; i++) {
// ...
if (iWantToRepeat) {
i--;
continue;
}
// ...
}
增强了for循环
for (Foo f : Bar) {
// ...
if (iWantToRepeat) {
// What can I put here?
}
// ...
}
有没有办法重复增强的for循环的迭代?我感觉可能有,因为它基于迭代器,如果我可以访问它们,我想我可以做到.
解决方法:
不,你不能重复循环中的元素.唯一的解决方案是在增强版中添加一个新循环.在我看来,这应该是即使在经典中也是如此,前后不是很干净,在查看代码时可能更难理解.
for (Foo f: bar) {
boolean notEnough=false;
do {
... //this code will be always executed once, at least
// change notEnough to true if you want to repeat
} while (notEnough);
}
要么
for (Foo f: bar) {
boolean notEnough=chooseIfYouWantToRunIt();
while(notEnough) {
... //this code can be not executed for a given element
}
}
标签:java,for-loop
来源: https://codeday.me/bug/20190715/1467044.html