如何在Java中打破嵌套循环?

2068

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

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

现在我该如何跳出这两个循环?我查看了类似的问题,但没有涉及到Java。我无法应用这些解决方案,因为大多数使用goto语句。
我不想将内部循环放在不同的方法中。
我不想返回循环。当我跳出时,我已经完成了循环块的执行。
37个回答

1
以下是一个示例,其中“break”语句在满足条件时将光标推出for循环。
public class Practice3_FindDuplicateNumber {

    public static void main(String[] args) {
        Integer[] inp = { 2, 3, 4, 3, 3 };
        Integer[] aux_arr = new Integer[inp.length];
        boolean isduplicate = false;
        for (int i = 0; i < aux_arr.length; i++) {

            aux_arr[i] = -1;

        }
        outer: for (int i = 0; i < inp.length; i++) {
            if (aux_arr[inp[i]] == -200) {
                System.out.println("Duplicate Found at index: " + i + " Carrying value: " + inp[i]);
                isduplicate = true;
                break outer;
            } else {
                aux_arr[inp[i]] = -200;
            }
        }

        for (Integer integer : aux_arr) {
            System.out.println(integer);
        }

        if (isduplicate == false) {
            System.out.println("No Duplicates!!!!!");
        } else {
            System.out.println("Duplicates!!!!!");
        }
    }

}

1
boolean condition = false;
for (Type type : types) {
    for (int i = 0; i < otherTypes.size && !condition; i ++) {
        condition = true; // If your condition is satisfied
    }
}

使用condition作为标志,表示处理完成。然后内部循环只在条件未满足时继续执行。无论如何,外部循环都会继续运行。

1

在某些情况下,我们可以有效地使用 while 循环。

Random rand = new Random();
// Just an example
for (int k = 0; k < 10; ++k) {
    int count = 0;
    while (!(rand.nextInt(200) == 100)) {
       count++;
    }

    results[k] = count;
}

0
如果有人正在寻找Kotlin添加标记循环的方法。
loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (...) break@loop
    }
}

源代码


0

甚至可以为外部循环创建一个标志,并在每次内部循环执行后进行检查,这可能是答案。

像这样:

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

0

通过检查内部循环的变量,可以使用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   
     } 
}

-10

我觉得使用标签会让代码看起来很像goto语句。这只是我的想法。

相反,可以在内部的for循环中抛出异常,并用try catch块封装这两个for循环。

就像这样:

try {
  // ...
  for(Object outerForLoop : objectsOuter) {
     // ...
     for (Object innerForLoop : objectsInner) {
        // ...
        if (isConditionTrue)
             throw new WrappedException("With some useful message. Probably some logging as well.");
     }
  }
  catch (WrappedException) {
        // Do something awesome or just don't do anything to swallow the exception.
  }

只是一种想法。我更喜欢这段代码,因为当它在生产环境中运行时,可以让我更好地记录日志(虽然这不是一个单词)。


11
在控制流中使用异常并不完全是最佳实践,因此这不是一个选项。 - boutta
@boutta 你为什么这么想? - Neuron
1
很多阅读和一些广受信任的人,如Bob大叔或Martin Fowler的意见。 - boutta
我知道这个问题特别针对Java,但有些人已经决定在语言设计中这样做了,这正是Python的StopIteration所用之处。 - Alvaro

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接