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

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

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

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

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


当前回答

你只需要使用标签来打破内部循环

public class Test {
public static void main(String[] args) {
    outerloop:
for (int i=0; i < 5; i++) {
  for (int j=0; j < 5; j++) {
    if (i * j > 6) {
      System.out.println("Breaking");
      break outerloop;
    }
    System.out.println(i + " " + j);
  }
}
System.out.println("Done");
}
}

其他回答

可以在循环周围使用命名块:

search: {
    for (Type type : types) {
        for (Type t : types2) {
            if (some condition) {
                // Do something and break...
                break search;
            }
        }
    }
}

使用函数:

public void doSomething(List<Type> types, List<Type> types2){
  for(Type t1 : types){
    for (Type t : types2) {
      if (some condition) {
         // Do something and return...
         return;
      }
    }
  }
}

通常在这种情况下,它属于更有意义的逻辑范围,比如说搜索或处理一些迭代的“for”对象,所以我通常使用函数方法:

public Object searching(Object[] types) { // Or manipulating
    List<Object> typesReferences = new ArrayList<Object>();
    List<Object> typesReferences2 = new ArrayList<Object>();

    for (Object type : typesReferences) {
        Object o = getByCriterion(typesReferences2, type);
        if(o != null) return o;
    }
    return null;
}

private Object getByCriterion(List<Object> typesReferences2, Object criterion) {
    for (Object typeReference : typesReferences2) {
        if(typeReference.equals(criterion)) {
             // here comes other complex or specific logic || typeReference.equals(new Object())
             return typeReference;
        }
    }
    return null;
}

主要缺点:

大约多出两行计算周期的消耗更多,这意味着从算法角度来看,计算速度更慢更多的打字工作

优点:

由于功能粒度,关注点分离的比率更高更高的重复使用率和控制搜索/操作逻辑这些方法不长,因此更紧凑,更容易理解更高的可读性

所以它只是通过一种不同的方法来处理这个案件。

基本上是问这个问题的作者:你对这种方法有什么看法?

最佳且简单的方法。。

outerloop:
for(int i=0; i<10; i++){
    // here we can break Outer loop by 
    break outerloop;

    innerloop:
    for(int i=0; i<10; i++){
        // here we can break innerloop by 
        break innerloop;
     }
}

您可以使用标签:

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