8

我有一个构造,其中我有一个for嵌套while在 Java 循环内的循环。有没有办法调用一个break语句,使其退出for循环和while循环?

4

5 回答 5

14

您可以为此使用“标记”中断。

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

于 2011-04-14T21:45:23.970 回答
3

您可以通过 3 种方式进行操作:

  • 您可以在方法中使用 while 和 for 循环,然后调用return
  • 您可以打破 for-loop 并设置一些标志,这将导致退出 while-loop
  • 使用标签(以下示例)

这是第三种方式的示例(带标签):

 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;
             }
         }
     }
  }

这个网站的例子

在我看来,第一个和第二个解决方案很优雅。一些程序员不喜欢标签。

于 2011-04-14T21:44:00.553 回答
2

标记中断

例如:

out:
    while(someCondition) {
        for(int i = 0; i < someInteger; i++) {
            if (someOtherCondition)
                break out;
        }
    }
于 2011-04-14T21:44:15.010 回答
1

使循环在函数调用中并从函数返回?

于 2011-04-14T21:41:41.227 回答
1

您应该能够为外部循环使用标签(在这种情况下)

所以像

    label:
        While()
        {
          for()
          {
             break label;
          }
        }
于 2011-04-14T21:44:15.877 回答