java for嵌套 break,在Java中,break如何与嵌套循环交互?

I know a break statement jumps out of a loop, but does it jump out of nested loops or just the one its currently in?

解决方案

Without any adornment, break will just break out of the innermost loop. Thus in this code:

while (true) { // A

while (true) { // B

break;

}

}

the break only exits loop B, so the code will loop forever.

However, Java has a feature called "named breaks" in which you can name your loops and then specify which one to break out of. For example:

A: while (true) {

B: while (true) {

break A;

}

}

This code will not loop forever, because the break explicitly leaves loop A.

Fortunately, this same logic works for continue. By default, continue executes the next iteration of the innermost loop containing the continue statement, but it can also be used to jump to outer loop iterations as well by specifying a label of a loop to continue executing.

In languages other than Java, for example, C and C++, this "labeled break" statement does not exist and it's not easy to break out of a multiply nested loop. It can be done using the goto statement, though this is usually frowned upon. For example, here's what a nested break might look like in C, assuming you're willing to ignore Dijkstra's advice and use goto:

while (true) {

while (true) {

goto done;

}

}

done:

// Rest of the code here.

Hope this helps!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值