如何退出两个嵌套循环? [英] How do exit two nested loops?
本文介绍了如何退出两个嵌套循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用Java已经有一段时间了,但是我对循环的学习还是有些欠缺.我知道如何创建存在于Java中的每个循环以及如何打破循环.但是,我最近想到了这一点:
I have been using Java for quite some time, yet my education in loops is somewhat lacking. I know how to create every loop that exists in java and break out of the loops as well. However, I've recently thought about this:
说我有两个嵌套循环.我可以只使用一个
break
语句打破两个循环吗?
Say I have two nested loops. Could I break out of both loops using just one
break
statement?
这是我到目前为止所拥有的.
Here is what I have so far.
int points = 0;
int goal = 100;
while (goal <= 100) {
for (int i = 0; i < goal; i++) {
if (points > 50) {
break; // For loop ends, but the while loop does not
}
// I know I could put a 'break' statement here and end
// the while loop, but I want to do it using just
// one 'break' statement.
points += i;
}
}
有没有办法做到这一点?
Is there a way to achieve this?
推荐答案
在Java中,您可以使用标签指定要中断/继续的循环:
In Java you can use a label to specify which loop to break/continue:
mainLoop:
while (goal <= 100) {
for (int i = 0; i < goal; i++) {
if (points > 50) {
break mainLoop;
}
points += i;
}
}
这篇关于如何退出两个嵌套循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文