Mil*_*ita 1 java for-loop break
你好,这是我的代码.
int counter=0;
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
System.out.println(++counter);
if(counter==11)
break;
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是当计数器等于11时如何结束两个循环?在这个例子中,我只是结束第二个循环.我知道如果我使用标签有一种方法,但还有其他方法吗?提前致谢.
Answer 1
Well, you can do it like this by adding the condition into both for loops.
for(int i=0;i<5 && counter!=11;i++)
{
for(int j=0;j<5 && counter!=11;j++)
{
System.out.println(++counter);
}
}
Run Code Online (Sandbox Code Playgroud)
But you are violating the DRY principle and likely triggering an IDE/Sonar warning.
Answer 2
Add an exception to your class
private static class LoopDoneException extends Exception { }
Run Code Online (Sandbox Code Playgroud)
Now throw it:
try {
for(int i=0;i<5;i++)
{
for(int j=0;j<5;j++)
{
System.out.println(++counter);
if (counter == 11) {
throw new LoopDoneException();
}
}
}
} catch (LoopDoneException e) {
// expected
}
}
Run Code Online (Sandbox Code Playgroud)
Answer 3
On reflection, I think teh best approach is a break statement referring to the label out.
out:
for (int i = 0; i < 5; i++) {
System.out.println("outer loop");
for (int j = 0; j < 5; j++) {
System.out.println("inner loop: " + ++counter);
if (counter == 11) {
break out;
}
}
}
Run Code Online (Sandbox Code Playgroud)
只需在外循环中有一个标志和条件,最初它被设置为false.一旦满足您的条件,只需将标志设置为true即可.所以外部for循环条件失败并退出.
boolean isDone = false;
int counter=0;
for(int i=0;i<5 && !isDone; i++)
{
for(int j=0;j<5;j++)
{
System.out.println(++counter);
if(counter==11){
isDone = true;
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
250 次 |
| 最近记录: |