【问题标题】:How do I break out of nested loops in Java?如何打破 Java 中的嵌套循环?
【发布时间】:2010-10-27 13:57:58
【问题描述】:

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

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

现在我怎样才能打破这两个循环?我看过类似的问题,但没有一个特别关注 Java。我无法应用这些解决方案,因为大多数使用 goto。

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

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

【问题讨论】:

    标签: java loops nested-loops


    【解决方案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;
    }
    

    【讨论】:

      【解决方案2】:

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

      像这样:

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

      【讨论】:

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

        使用condition 作为处理完成时的标志。然后内部循环仅在未满足条件时继续。无论哪种方式,外部循环都会继续运行。

        【讨论】:

          【解决方案4】:

          下面是一个例子,只要满足条件,“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!!!!!");
                  }
              }
          
          }
          

          【讨论】:

            【解决方案5】:

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

            【讨论】:

              【解决方案6】:

              我觉得使用标签使代码看起来很像 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.
                }
              

              只是一个想法。我更喜欢这段代码,因为当它在生产中运行时,它为我提供了更好的可记录性(就像一个词一样)。

              【讨论】:

              • 对控制流使用异常并不是最佳实践。所以,不,这是没有选择的。
              • @boutta 是什么让你这么认为?
              • 大量阅读和一些广受信任的人的意见,如 Bob oder Martin Fowler 叔叔。
              • 我知道这个问题是专门针对java的,但是有些人已经决定在语言设计中这样做,这正是python的StopIteration的目的跨度>
              猜你喜欢
              • 2012-03-30
              • 2012-01-19
              • 2019-01-30
              • 2022-01-14
              • 1970-01-01
              • 2012-11-30
              • 1970-01-01
              相关资源
              最近更新 更多