java Java多级中断
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5670051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java multi-level break
提问by themaestro
I have a construct where I have a for
loop nested inside of a while
loop in Java. Is there a way to call a break
statement such that it exits both the for
loop and the while
loop?
我有一个构造,其中我有一个for
嵌套while
在 Java 循环中的循环。有没有办法调用一个break
语句,使它既退出for
循环又退出while
循环?
回答by Guido Anselmi
You can use a 'labeled' break for this.
您可以为此使用“标记”中断。
class BreakWithLabelDemo {
public static void main(String[] args) {
int[][] arrayOfInts = { { 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) {
System.out.println("Found " + searchfor +
" at " + i + ", " + j);
} else {
System.out.println(searchfor
+ " not in the array");
}
}
}
}
Taken from: http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
取自:http: //download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
回答by lukastymo
You can do it in 3 ways:
您可以通过 3 种方式进行操作:
- You can have while and for loops inside method, and then just call
return
- You can break for-loop and set some flag which will cause exit in while-loop
- Use label (example below)
- 您可以在方法内部使用 while 和 for 循环,然后调用
return
- 您可以中断 for 循环并设置一些标志,这将导致在 while 循环中退出
- 使用标签(以下示例)
This is example for 3rd way (with label):
这是第三种方式的示例(带标签):
public void someMethod() {
// ...
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length; j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
}
example from this site
这个网站的例子
In my opinion 1st and 2nd solution is elegant. Some programmers don't like labels.
在我看来,第一个和第二个解决方案很优雅。有些程序员不喜欢标签。
回答by T.K.
For example:
例如:
out:
while(someCondition) {
for(int i = 0; i < someInteger; i++) {
if (someOtherCondition)
break out;
}
}
回答by korymiller
You should able to use a label for the outer loop (while in this case)
您应该能够为外循环使用标签(在这种情况下)
So something like
所以像
label:
While()
{
for()
{
break label;
}
}
回答by Jean-Bernard Pellerin
Make the loop be inside a function call and return from the function?
使循环在函数调用中并从函数返回?