我有一个构造,其中我在Java中的for
循环内嵌套了while
循环。有没有办法调用break
语句,使其退出for
循环和while
循环?
答案 0 :(得分:13)
您可以使用“标记”中断。
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");
}
}
}
取自:http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html
答案 1 :(得分:3)
您可以通过3种方式实现:
return
这是第三种方式(带标签)的例子:
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;
}
}
}
}
的示例
在我看来,第一和第二个解决方案很优雅。有些程序员不喜欢标签。
答案 2 :(得分:2)
例如:
out:
while(someCondition) {
for(int i = 0; i < someInteger; i++) {
if (someOtherCondition)
break out;
}
}
答案 3 :(得分:1)
使循环在函数调用中并从函数返回?
答案 4 :(得分:1)
你应该能够为外循环使用标签(在这种情况下)(
)类似
label:
While()
{
for()
{
break label;
}
}