如何在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个回答

5
如果它在某个函数内部,为什么不直接返回它呢:
for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
            return value;
         }
    }
}

我更喜欢这种模式。通常会让我将循环拆分为一个单独的函数。每次这样做后,我的代码总是变得更好,因此出于这个原因,我真的很喜欢这个答案。 - Bill K

5

最佳且易于实施的方法...

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

6
这些打破的例子在我看来并不是很有帮助,因为即使没有标签,它们也会在相同的位置打破。同时,拥有可执行的代码总是很好的,但你的代码无法执行内部循环,这一点也不好。 - Neuron
我本来也想打同样的话。在这种情况下,标签有点无用。 - Taslim Oseni

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

4

breakcontinuelabel的演示:

Java关键字breakcontinue有一个默认值,即“最近的循环”,今天,在使用Java几年后,我终于理解了它!

尽管它似乎使用得比较少,但它仍然非常有用。

import org.junit.Test;

/**
 * Created by cui on 17-5-4.
 */

public class BranchLabel {
    @Test
    public void test() {
        System.out.println("testBreak");
        testBreak();

        System.out.println("testBreakLabel");
        testBreakLabel();

        System.out.println("testContinue");
        testContinue();
        System.out.println("testContinueLabel");
        testContinueLabel();
    }

    /**
     testBreak
     a=0,b=0
     a=0,b=1
     a=1,b=0
     a=1,b=1
     a=2,b=0
     a=2,b=1
     a=3,b=0
     a=3,b=1
     a=4,b=0
     a=4,b=1
     */
    public void testBreak() {
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                if (b == 2) {
                    break;
                }
                System.out.println("a=" + a + ",b=" + b);
            }
        }
    }

    /**
     testContinue
     a=0,b=0
     a=0,b=1
     a=0,b=3
     a=0,b=4
     a=1,b=0
     a=1,b=1
     a=1,b=3
     a=1,b=4
     a=2,b=0
     a=2,b=1
     a=2,b=3
     a=2,b=4
     a=3,b=0
     a=3,b=1
     a=3,b=3
     a=3,b=4
     a=4,b=0
     a=4,b=1
     a=4,b=3
     a=4,b=4
     */
    public void testContinue() {
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                if (b == 2) {
                    continue;
                }
                System.out.println("a=" + a + ",b=" + b);
            }
        }
    }

    /**
     testBreakLabel
     a=0,b=0,c=0
     a=0,b=0,c=1
     * */
    public void testBreakLabel() {
        anyName:
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                for (int c = 0; c < 5; c++) {
                    if (c == 2) {
                        break anyName;
                    }
                    System.out.println("a=" + a + ",b=" + b + ",c=" + c);
                }
            }
        }
    }

    /**
     testContinueLabel
     a=0,b=0,c=0
     a=0,b=0,c=1
     a=1,b=0,c=0
     a=1,b=0,c=1
     a=2,b=0,c=0
     a=2,b=0,c=1
     a=3,b=0,c=0
     a=3,b=0,c=1
     a=4,b=0,c=0
     a=4,b=0,c=1
     */
    public void testContinueLabel() {
        anyName:
        for (int a = 0; a < 5; a++) {
            for (int b = 0; b < 5; b++) {
                for (int c = 0; c < 5; c++) {
                    if (c == 2) {
                        continue anyName;
                    }
                    System.out.println("a=" + a + ",b=" + b + ",c=" + c);
                }
            }
        }
    }
}

3

for (int j = 0; j < 5; j++) //内部循环 应该被替换为 for (int j = 0; j < 5 && !exitloops; j++)

在这种情况下,如果条件为 True,则应该完全退出嵌套循环。但是,如果我们仅将 exitloops 应用于上层的 loop

 for (int i = 0; i < 5 && !exitloops; i++) //upper loop

然后内部循环将继续,因为没有额外的标志来通知这个内部循环退出。
示例:如果i=3j=2,则条件为false。但在内部循环的下一次迭代中,j=3,然后条件(i*j)变为9,这是true,但内部循环将继续,直到j变为5
因此,必须对内部循环也使用exitloops
boolean exitloops = false;
for (int i = 0; i < 5 && !exitloops; i++) { //here should exitloops as a Conditional Statement to get out from the loops if exitloops become true. 
    for (int j = 0; j < 5 && !exitloops; j++) { //here should also use exitloops as a Conditional Statement. 
        if (i * j > 6) {
            exitloops = true;
            System.out.println("Inner loop still Continues For i * j is => "+i*j);
            break;
        }
        System.out.println(i*j);
    }
}

2

Java不像C++一样有goto功能。但是,goto在Java中仍然是一个保留关键字。他们可能会在将来实现它。对于你的问题,答案是Java中有一种叫做标签的东西,你可以在其上应用continuebreak语句。下面是代码:

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

2

像 @1800 INFORMATION 的建议一样,将打破内部循环的条件作为外部循环的条件:

boolean hasAccess = false;
for (int i = 0; i < x && hasAccess == false; i++){
    for (int j = 0; j < y; j++){
        if (condition == true){
            hasAccess = true;
            break;
        }
    }
}

2

如果这是一个新的实现,您可以尝试将逻辑重写为if-else_if-else语句。

while(keep_going) {

    if(keep_going && condition_one_holds) {
        // Code
    }
    if(keep_going && condition_two_holds) {
        // Code
    }
    if(keep_going && condition_three_holds) {
        // Code
    }
    if(keep_going && something_goes_really_bad) {
        keep_going=false;
    }
    if(keep_going && condition_four_holds) {
        // Code
    }
    if(keep_going && condition_five_holds) {
        // Code
    }
}

否则,您可以尝试在特定条件发生时设置标志,并在每个循环条件中检查该标志。
something_bad_has_happened = false;
while(something is true && !something_bad_has_happened){
    // Code, things happen
    while(something else && !something_bad_has_happened){
        // Lots of code, things happens
        if(something happened){
            -> Then control should be returned ->
            something_bad_has_happened=true;
            continue;
        }
    }
    if(something_bad_has_happened) { // The things below will not be executed
        continue;
    }

    // Other things may happen here as well, but they will not be executed
    //  once control is returned from the inner cycle.
}

看这里!虽然简单的break语句无法满足需求,但可以使用continue语句来实现。

如果你只是想在Java中移植逻辑并使代码正常工作,可以尝试使用标签


1

你只需使用标签来中断内部循环

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

1
你可以做以下事情:

  1. set a local variable to false

  2. set that variable true in the first loop, when you want to break

  3. then you can check in the outer loop, that whether the condition is set then break from the outer loop as well.

    boolean isBreakNeeded = false;
    for (int i = 0; i < some.length; i++) {
        for (int j = 0; j < some.lengthasWell; j++) {
            //want to set variable if (){
            isBreakNeeded = true;
            break;
        }
    
        if (isBreakNeeded) {
            break; //will make you break from the outer loop as well
        }
    }
    

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