【问题标题】:how to transfer the control to outer loop from inner loop after some conds are checked and some operations are done?在检查几秒钟并完成一些操作后,如何将控制从内循环转移到外循环?
【发布时间】:2013-08-11 16:57:51
【问题描述】:

我想在执行 if 块后将控制权转移到外部 for 循环(i 循环)。即我想跳过内部循环(j循环)的所有剩余迭代并将控制权转移到外部循环。(i循环)请帮助

for(int i=0;i<ana.length;i++) {
    for(int j=i+1;j<ana.length;j++) {

        if(a.isAnagram(ana[i],ana[j])) {
            temp=ana[i+1];
            ana[i+1]=ana[j];
            for(int p=i+2;p<j;p++) {
                ana[p+1]=ana[p];
            }
            ana[i+2]=temp;
        }
    }
}

【问题讨论】:

  • break?在需要的地方使用标签。方法如下:stackoverflow.com/questions/886955/…
  • 使用中断并继续。
  • 即使是基本的谷歌搜索也会提供有关如何解决此问题的信息。 -1

标签: java for-loop controls transfer outer-join


【解决方案1】:

您可以使用break with label

这是 Java 教程中的示例:search 是此处的标签。

class BreakWithLabelDemo {
    public static void main(String[] args) {

        int[][] arrayOfInts = { 
            { 32, 87, 3, 589 },
            { 12, 1076, 2000, 8 },
            { 622, 127, 77, 955 }
        };
        int searchfor = 12;

        int i;
        int j = 0;
        boolean foundIt = false;

    search:
        for (i = 0; i < arrayOfInts.length; i++) {
            for (j = 0; j < arrayOfInts[i].length;
                 j++) {
                if (arrayOfInts[i][j] == searchfor) {
                    foundIt = true;
                    break search;
                }
            }
        }

        if (foundIt) {
            System.out.println("Found " + searchfor + " at " + i + ", " + j);
        } else {
            System.out.println(searchfor + " not in the array");
        }
    }
}

【讨论】:

    【解决方案2】:

    在 if 块的末尾使用“break”语句。这将跳过“j”循环的剩余迭代,并运行“i”循环的下一次迭代。

    for(int i=0;i<ana.length;i++)
    {
       for(int j=i+1;j<ana.length;j++)
       {
          if(a.isAnagram(ana[i],ana[j]))
          {
             temp=ana[i+1];
             ana[i+1]=ana[j];
             for(int p=i+2;p<j;p++)
             {
                ana[p+1]=ana[p];
             }
             ana[i+2]=temp;
             break;
          }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-20
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多