java+enhanced+loop_java – 在enhanced-for循环中重复迭代

定期循环

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值