简体   繁体   English

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

[英]How do I break out of nested loops in Java?

I've got a nested loop construct like this:我有一个这样的嵌套循环结构:

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

Now how can I break out of both loops?现在我怎样才能跳出这两个循环? I've looked at similar questions, but none concerns Java specifically.我看过类似的问题,但没有一个专门涉及 Java。 I couldn't apply these solutions because most used gotos.我无法应用这些解决方案,因为大多数使用 goto。

I don't want to put the inner loop in a different method.我不想将内部循环放在不同的方法中。

I don't want to return the loops.我不想返回循环。 When breaking I'm finished with the execution of the loop block.中断时,我完成了循环块的执行。

Like other answerers, I'd definitely prefer to put the loops in a different method, at which point you can just return to stop iterating completely.像其他回答者一样,我绝对更喜欢将循环放在不同的方法中,此时您可以返回以完全停止迭代。 This answer just shows how the requirements in the question can be met.此答案仅显示如何满足问题中的要求。

You can use break with a label for the outer loop.您可以将break与标签一起用于外循环。 For example:例如:

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

This prints:这打印:

0 0
0 1
0 2
0 3
0 4
1 0
1 1
1 2
1 3
1 4
2 0
2 1
2 2
2 3
Breaking
Done

Technically the correct answer is to label the outer loop.从技术上讲,正确的答案是标记外循环。 In practice if you want to exit at any point inside an inner loop then you would be better off externalizing the code into a method (a static method if needs be) and then call it.实际上,如果您想在内循环内的任何一点退出,那么最好将代码外部化为一个方法(如果需要,则为静态方法)然后调用它。

That would pay off for readability.这将为可读性带来回报。

The code would become something like that:代码会变成这样:

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

Matching the example for the accepted answer:匹配已接受答案的示例:

 public class Test {
    public static void main(String[] args) {
        loop();
        System.out.println("Done");
    }

    public static void loop() {
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
                if (i * j > 6) {
                    System.out.println("Breaking");
                    return;
                }
                System.out.println(i + " " + j);
            }
        }
    }
}

You can use a named block around the loops:您可以在循环周围使用命名块:

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

I never use labels.我从不使用标签。 It seems like a bad practice to get into.进入似乎是一种不好的做法。 Here's what I would do:这是我会做的:

boolean finished = false;
for (int i = 0; i < 5 && !finished; i++) {
    for (int j = 0; j < 5; j++) {
        if (i * j > 6) {
            finished = true;
            break;
        }
    }
}

You can use labels:您可以使用标签:

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

Use a function:使用一个函数:

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

You can use a temporary variable:您可以使用临时变量:

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

Depending on your function, you can also exit/return from the inner loop:根据您的功能,您还可以从内部循环退出/返回:

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

If you don't like break s and goto s, you can use a "traditional" for loop instead the for-in, with an extra abort condition:如果您不喜欢break s 和goto s,则可以使用“传统” for 循环代替 for-in,并带有额外的中止条件:

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

I needed to do a similar thing, but I chose not to use the enhanced for loop to do it.我需要做类似的事情,但我选择不使用增强的 for 循环来做它。

int s = type.size();
for (int i = 0; i < s; i++) {
    for (int j = 0; j < t.size(); j++) {
        if (condition) {
            // do stuff after which you want 
            // to completely break out of both loops
            s = 0; // enables the _main_ loop to terminate
            break;
        }
    }
}

I prefer to add an explicit "exit" to the loop tests.我更喜欢在循环测试中添加一个明确的“退出”。 It makes it clear to any casual reader that the loop may terminate early.它让任何普通读者都清楚循环可能会提前终止。

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

Java 8 Stream solution: Java 8 Stream解决方案:

List<Type> types1 = ...
List<Type> types2 = ...

types1.stream()
      .flatMap(type1 -> types2.stream().map(type2 -> new Type[]{type1, type2}))
      .filter(types -> /**some condition**/)
      .findFirst()
      .ifPresent(types -> /**do something**/);

Usually in such cases, it is coming in scope of more meaningful logic, let's say some searching or manipulating over some of the iterated 'for'-objects in question, so I usually use the functional approach:通常在这种情况下,它会进入更有意义的逻辑范围,比如说搜索或操作一些有问题的迭代“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;
}

Major cons:主要缺点:

  • roughly twice more lines大约多两倍
  • more consumption of computing cycles, meaning it is slower from algorithmic point-of-view更多的计算周期消耗,这意味着从算法的角度来看它更慢
  • more typing work更多打字工作

The pros:优点:

  • the higher ratio to separation of concerns because of functional granularity由于功能粒度,更高的关注点分离比率
  • the higher ratio of re-usability and control of searching/manipulating logic without更高的可重用性和控制搜索/操作逻辑的比率,而无需
  • the methods are not long, thus they are more compact and easier to comprehend方法不长,因此更紧凑,更容易理解
  • higher ratio of readability更高的可读性

So it is just handling the case via a different approach.所以它只是通过不同的方法处理案例。

Basically a question to the author of this question: what do you consider of this approach?基本上是对这个问题的作者的一个问题:您如何看待这种方法?

Labeled break concept is used to break out nested loops in java, by using labeled break you can break nesting of loops at any position.标记中断概念用于在 Java 中中断嵌套循环,通过使用标记中断,您可以在任何位置中断循环嵌套。 Example 1:示例 1:

loop1:
 for(int i= 0; i<6; i++){
    for(int j=0; j<5; j++){
          if(i==3)
            break loop1;
        }
    }

suppose there are 3 loops and you want to terminate the loop3: Example 2:假设有 3 个循环并且您想终止循环 3:示例 2:

loop3: 
for(int i= 0; i<6; i++){
loop2:
  for(int k= 0; k<6; k++){
loop1:
    for(int j=0; j<5; j++){
          if(i==3)
            break loop3;
        }
    }
}

You can break from all loops without using any label: and flags.您可以在不使用任何标签:和标志的情况下中断所有循环。

It's just tricky solution.这只是棘手的解决方案。

Here condition1 is the condition which is used to break from loop K and J. And condition2 is the condition which is used to break from loop K , J and I.这里的条件1是用于从循环K和J中断的条件。条件2是用于从循环K、J和I中断的条件。

For example:例如:

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

Use Labels.使用标签。

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

Refer to this article参考这篇文章

Best and Easy Method..最好和最简单的方法..

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

Demo演示

public static void main(String[] args) {
    outer:
    while (true) {
        while (true) {
            break outer;
        }
    }
}
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;
    }
}

Another one solution, mentioned without example (it actually works in prod code).另一种解决方案,在没有示例的情况下提到(它实际上适用于产品代码)。

try {
    for (Type type : types) {
        for (Type t : types2) {
            if (some condition #1) {
                // Do something and break the loop.
                throw new BreakLoopException();
            }
        }
    }
}
catch (BreakLoopException e) {
    // Do something on look breaking.
}

Of course BreakLoopException should be internal, private and accelerated with no-stack-trace:当然BreakLoopException应该是内部的、私有的并且通过无堆栈跟踪加速:

private static class BreakLoopException extends Exception {
    @Override
    public StackTraceElement[] getStackTrace() {
        return new StackTraceElement[0];
    }
}

Rather unusual approach but in terms of code length ( not performance ) this is the easiest thing you could do:相当不寻常的方法,但就代码长度(不是性能)而言,这是您可以做的最简单的事情:

for(int i = 0; i++; i < j) {
    if(wanna exit) {
        i = i + j; // if more nested, also add the 
                   // maximum value for the other loops
    }
}

If it is inside some function why don't you just return it:如果它在某个函数内,为什么不直接返回它:

for (Type type : types) {
    for (Type t : types2) {
         if (some condition) {
            return value;
         }
    }
}

Demo for break , continue , and label : breakcontinuelabel演示:

Java keywords break and continue have a default value. Java 关键字breakcontinue有一个默认值。 It's the "nearest loop", and today, after a few years of using Java, I just got it!这是“最近的循环”,今天,在使用 Java 几年后,我刚刚明白了!

It's seem used rare, but useful.它似乎很少使用,但很有用。

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

for (int j = 0; j < 5; j++) //inner loop should be replaced with for (int j = 0; j < 5 && !exitloops; j++) . for (int j = 0; j < 5; j++) //inner loop应该替换for (int j = 0; j < 5 && !exitloops; j++)

Here, in this case complete nested loops should be exit if condition is True .在这里,在这种情况下,如果条件为True则应退出完整的嵌套循环。 But if we use exitloops only to the upper loop但是如果我们只对上层loop使用exitloops

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

Then inner loop will continues, because there is no extra flag that notify this inner loop to exit.然后内循环会继续,因为没有额外的标志来通知这个内循环退出。

Example : if i = 3 and j=2 then condition is false .示例:如果i = 3j=2则条件为false But in next iteration of inner loop j=3 then condition (i*j) become 9 which is true but inner loop will be continue till j become 5 .但是在内循环j=3下一次迭代中,条件(i*j)变为9 ,这是true但内循环将继续直到j变为5

So, it must use exitloops to the inner loops too.因此,它也必须使用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);
    }
}

Using 'break' keyword alone is not the appropriate way when you need to exit from more than one loops.当您需要退出多个循环时,单独使用 'break' 关键字不是合适的方法。 You can exit from immediate loop No matter with how many loops your statement is surrounded with.无论您的语句周围有多少个循环,您都可以退出立即循环。 You can use 'break' with a label!您可以使用带有标签的“break”! Here I've used the label "abc" You can write your code as following, within any function in Java在这里,我使用了标签“abc”您可以在 Java 中的任何函数中编写如下代码

This code shows how to exit from the most outer loop此代码显示如何从最外层循环退出

 abc: 
    for (int i = 0; i < 10; i++) { 
        for (int j = 0; j < 10; j++) { 
           for (int k = 0; k < 10; k++) { 
              if (k == 1){
                 break abc;
              } 
        } 
    } 
}

Also you can use break statement to exit from any loop in a nested loop.您也可以使用 break 语句退出嵌套循环中的任何循环。

    for (int i = 0; i < 10; i++) { 
       abc:for (int j = 0; j < 10; j++) { 
           for (int k = 0; k < 10; k++) { 
              if (k == 1){
                 break abc;
              } 
        } 
    } 
}

The following code shows an example of exiting from the innermost loop.以下代码显示了从最内层循环退出的示例。 In other works,after executing the following code, you are at the outside of the loop of 'k' variables and still inside the loop of 'j' and 'i' variables.在其他作品中,执行以下代码后,您处于'k'变量循环的外部,并且仍在'j'和'i'变量循环内。

    for (int i = 0; i < 10; i++) { 
        for (int j = 0; j < 10; j++) { 
           for (int k = 0; k < 10; k++) { 
              if (k == 1){
                 break;
              } 
        } 
    } 
}

Like @1800 INFORMATION suggestion, use the condition that breaks the inner loop as a condition on the outer loop:像@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;
        }
    }
}

If it's a new implementation, you can try rewriting the logic as if-else_if-else statements.如果是新的实现,可以尝试将逻辑重写为 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
    }
}

Otherwise you can try setting a flag when that special condition has occured and check for that flag in each of your loop-conditions.否则,您可以尝试在发生该特殊条件时设置一个标志,并在每个循环条件中检查该标志。

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

HERE!这里! So, while a simple break will not work, it can be made to work using continue .因此,虽然简单的中断不起作用,但可以使用continue使其工作。

If you are simply porting the logic from one programming language to Java and just want to get the thing working you can try using labels .如果您只是将逻辑从一种编程语言移植到 Java 并且只是想让它工作,您可以尝试使用标签

Java does not have a goto feature like there is in C++. Java 没有像 C++ 那样的 goto 功能。 But still, goto is a reserved keyword in Java.但是, goto仍然是 Java 中的保留关键字。 They might implement it in the future.他们可能会在未来实施。 For your question, the answer is that there is something called label in Java to which you can apply a continue and break statement.对于您的问题,答案是 Java 中有一种叫做 label 的东西,您可以对其应用continuebreak语句。 Find the code below:找到下面的代码:

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

It's fairly easy to use label , You can break the outer loop from inner loop using the label, Consider the example below,使用label相当容易,您可以使用label将外循环与内循环分开,请考虑下面的示例,

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

Another approach is to use the breaking variable/flag to keep track of required break.另一种方法是使用中断变量/标志来跟踪所需的中断。 consider the following example.考虑以下示例。

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

However, I prefer using the first approach.但是,我更喜欢使用第一种方法。

You just use label for breaking inner loops您只需使用标签来打破内部循环

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

I've got a nested loop construct like this:我有一个像这样的嵌套循环构造:

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

Now how can I break out of both loops?现在我该如何摆脱这两个循环? I've looked at similar questions, but none concerns Java specifically.我看过类似的问题,但没有一个是Java特有的。 I couldn't apply these solutions because most used gotos.我无法应用这些解决方案,因为大多数使用的gotos。

I don't want to put the inner loop in a different method.我不想将内部循环使用其他方法。

I don't want to rerun the loops.我不想重新运行循环。 When breaking I'm finished with the execution of the loop block.中断时,我完成了循环块的执行。

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

Use condition as a flag for when you are done processing. 使用condition作为完成处理时的标记。 Then the inner loop only continues on while the condition has not been met. 然后,内部循环仅在不满足条件的情况下继续进行。 Either way, the outer loop will keep on chuggin'. 无论哪种方式,外部循环都将持续不断。

I've got a nested loop construct like this:我有一个像这样的嵌套循环构造:

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

Now how can I break out of both loops?现在我该如何摆脱这两个循环? I've looked at similar questions, but none concerns Java specifically.我看过类似的问题,但没有一个是Java特有的。 I couldn't apply these solutions because most used gotos.我无法应用这些解决方案,因为大多数使用的gotos。

I don't want to put the inner loop in a different method.我不想将内部循环使用其他方法。

I don't want to rerun the loops.我不想重新运行循环。 When breaking I'm finished with the execution of the loop block.中断时,我完成了循环块的执行。

You can do the following:您可以执行以下操作:

  1. set a local variable to false将局部变量设置为false

  2. set that variable true in the first loop, when you want to break当您想中断时,在第一个循环中将该变量设置为true

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

Below is an example where "break" statement pushes the cursor out of the for loop whenever the condition is met.下面是一个示例,其中只要满足条件,“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!!!!!");
        }
    }

}

Check if the inner loop is exited with an if statement, by checking the inner loop's variable.通过检查内部循环的变量,检查内部循环是否使用 if 语句退出。 You could also create another variable such as a boolean to check if the inner loop is exited.您还可以创建另一个变量(例如布尔值)来检查内部循环是否已退出。

In this example it uses the inner loop's variable to check if it has been exited:在这个例子中,它使用内部循环的变量来检查它是否已经退出:

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

I feel using labels makes the code seem very much like a goto statement.我觉得使用标签使代码看起来很像 goto 语句。 This is just a thought.这只是一个想法。

Instead, throw an exception at the inner for loop and encapsulate the two for loops with a try catch block.相反,在内部for循环中抛出异常并用 try catch 块封装两个for循环。

Something like就像是

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

Just a thought.只是一个想法。 I prefer this code since it gives me better loggability (like that's a word) for me when this is being run in production or something.我更喜欢这段代码,因为当它在生产环境中运行时,它为我提供了更好的可记录性(就像一个词)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM