问题描述
|
我有一个构造,其中在Java中的
while
循环内嵌套了一个for
循环。有没有办法调用call2ѭ语句,使其既退出for
循环又退出while
循环?
解决方法
您可以为此使用\'labeled \'中断。
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
,您可以通过3种方式来做到这一点:
您可以在方法内部有while和for循环,然后只需调用return
您可以中断for循环并设置一些标志,这将导致在while循环中退出
使用标签(下面的示例)
这是第三种方式的示例(带有标签):
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;
}
}
}
}
这个网站的例子
我认为第一和第二解决方案很优雅。一些程序员不喜欢标签。
,标记的休息
例如:
out:
while(someCondition) {
for(int i = 0; i < someInteger; i++) {
if (someOtherCondition)
break out;
}
}
,使循环位于函数调用内并从函数返回?
,您应该能够为外循环使用标签(在这种情况下)
所以像
label:
While()
{
for()
{
break label;
}
}