有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

嵌套循环继续java

我有以下的for循环:

for (int i = 0; i<arr.length;i++) {
    for(int j =0; j<someArr.length; j++) {
       //after this inner loop, continue with the other loop
    }
}

我想打破内循环,继续外循环的迭代。我该怎么做


共 (3) 个答案

  1. # 1 楼答案

    你可以休息

    for (int i = 0; i<arr.length;i++) {
        for(int j =0; j<someArr.length; j++) {
           //after this inner loop, continue with the other loop
           break;
        }
    // Executed after the break instruction
    }
    
  2. # 2 楼答案

    一般来说,您可以使用lablebreak的组合来跳转到您想要的位置

    OUTER_LOOP: for (int i = 0; i<arr.length;i++) {
        for(int j =0; j<someArr.length; j++) {
           //after this inner loop, continue with the other loop
         break OUTER_LOOP;
    
        }
    }
    

    如果你想在外循环中这样做,把标签放在你想跳转到的地方(当前循环之外),并在break语句中使用标签

     for (int i = 0; i<arr.length;i++) {
        //line code 1
       OUTER_LOOP: // line code 2
        for(int j =0; j<someArr.length; j++) {
           //after this inner loop, continue with the other loop
         break OUTER_LOOP;
    
        }
    }
    
  3. # 3 楼答案

    break不会停止所有迭代

    因此,如果执行以下操作,则只会break退出嵌套循环(第二个for),并继续第一个for循环的当前迭代:

    for (int i = 0; i < arr.length; i++) {
        for (int j = 0; j < someArr.length; j++) {
           break;
           // NOT executed after the break instruction
        }
        // Executed after the break instruction
    }