如何突破Java中的嵌套循环?

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

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

如今如何摆脱两个循环? 我看过相似的问题,但没有一个是Java特有的。 我没法应用这些解决方案,由于大多数使用的gotos。 java

我不想将内部循环使用其余方法。 ide

我不想从新运行循环。 中断时,我完成了循环块的执行。 oop


#1楼

甚至为外循环建立一个标志并在每次执行内循环后检查是否能够解决问题。 spa

像这样: code

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

#2楼

boolean broken = false; // declared outside of the loop for efficiency
for (Type type : types) {
    for (Type t : types2) {
        if (some condition) {
            broken = true;
            break;
        }
    }

    if (broken) {
        break;
    }
}

#3楼

若是您不喜欢breakgoto ,则能够使用“传统” for循环而不是for-in,并带有额外的停止条件: htm

int a, b;
bool abort = false;
for (a = 0; a < 10 && !abort; a++) {
    for (b = 0; b < 10 && !abort; b++) {
        if (condition) {
            doSomeThing();
            abort = true;
        }
    }
}

#4楼

您能够不使用任何label:和标志而中断全部循环。 blog

这只是棘手的解决方案。 ci

这里的condition1是用于中断循环K和J的条件。而condition2是用于中断循环K,J和I的条件。 get

例如:

public class BreakTesting {
    public static void main(String[] args) {
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                for (int k = 0; k < 9; k++) {
                    if (condition1) {
                        System.out.println("Breaking from Loop K and J");
                        k = 9;
                        j = 9;
                    }
                    if (condition2) {
                        System.out.println("Breaking from Loop K, J and I");
                        k = 9;
                        j = 9;
                        i = 9;
                    }
                }
            }
        }
        System.out.println("End of I , J , K");
    }
}

#5楼

使用标签。

INNER:for(int j = 0; j < numbers.length; j++) {
    System.out.println("Even number: " + i + ", break  from INNER label");
    break INNER;
}

参考这篇文章

相关文章
相关标签/搜索