Java多级休息

时间:2011-04-14 21:40:21

标签: java loops break multi-level

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

5 个答案:

答案 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种方式实现:

  • 您可以在方法内部使用while和for循环,然后只需调用return
  • 你可以打破for循环并设置一些标志,这将导致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;
             }
         }
     }
  }

来自this site

的示例

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

答案 2 :(得分:2)

Labelled Breaks

例如:

out:
    while(someCondition) {
        for(int i = 0; i < someInteger; i++) {
            if (someOtherCondition)
                break out;
        }
    }

答案 3 :(得分:1)

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

答案 4 :(得分:1)

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

类似

    label:
        While()
        {
          for()
          {
             break label;
          }
        }