我有一个这样的嵌套循环构造:

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
             // Do something and break...
             break; // Breaks out of the inner loop
         }
    }
}

现在我怎样才能打破这两个循环?我已经研究过类似的问题,但没有一个与Java相关。我无法应用这些解决方案,因为大多数人都使用goto。

我不想将内部循环放在不同的方法中。

我不想返回循环。当中断时,我完成了循环块的执行。


当前回答

我更喜欢在循环测试中添加一个明确的“出口”。它清楚地表明循环可能提前终止的任何临时读取器。

boolean earlyExit = false;
for(int i = 0 ; i < 10 && !earlyExit; i++) {
     for(int j = 0 ; i < 10 && !earlyExit; j++) { earlyExit = true; }
}

其他回答

您可以使用标签:

label1: 
for (int i = 0;;) {
    for (int g = 0;;) {
      break label1;
    }
}

使用标签非常简单,您可以使用标签将外循环与内循环分开,请考虑下面的示例,

public class Breaking{
    public static void main(String[] args) {
        outerscope:
        for (int i=0; i < 5; i++) {
            for (int j=0; j < 5; j++) {
                if (condition) {
                    break outerscope;
                }
            }
        }
    }
}

另一种方法是使用中断变量/标志来跟踪所需的中断。考虑以下示例。

public class Breaking{ 
    public static void main(String[] args) {
        boolean isBreaking = false;
        for (int i=0; i < 5; i++) {
            for (int j=0; j < 5; j++) {
                if (condition) {
                    isBreaking = true;
                    break;
                }
            }
            if(isBreaking){
                break;
            }
        }
    }
}

然而,我更喜欢使用第一种方法。

通过检查内部循环的变量,检查内部循环是否使用if语句退出。您还可以创建另一个变量,例如布尔值,以检查内部循环是否已退出。

在本例中,它使用内部循环的变量来检查是否已退出:

int i, j;
for(i = 0; i < 7; i++){

for(j = 0; j < 5; j++) {

     if (some condition) {
         // Do something and break...
         break; // Breaks out of the inner loop
     }
}
     if(j < 5){    // Checks if inner loop wasn't finished
     break;    // Breaks out of the outer loop   
     } 
}

Java不像C++那样具有goto特性。但在Java中,goto仍然是一个保留关键字。他们可能会在未来实施它。对于您的问题,答案是Java中有一种叫做标签的东西,您可以对其应用continue和break语句。查找以下代码:

public static void main(String ...args) {
    outerLoop: for(int i=0;i<10;i++) {
    for(int j=10;j>0;j--) {
        System.out.println(i+" "+j);
        if(i==j) {
            System.out.println("Condition Fulfilled");
            break outerLoop;
        }
    }
    }
    System.out.println("Got out of the outer loop");
}

Demo

public static void main(String[] args) {
    outer:
    while (true) {
        while (true) {
            break outer;
        }
    }
}