-2

i want to transfer the control to outer for loop(i loop) after if block is executed. ie i wanna skip all the remaining iterations for inner loop(j loop) and transfer the control to outer one.(i loop) pls help

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;
        }
    }
}
Richard Sitze
  • 8,262
  • 3
  • 36
  • 48

2 Answers2

1

You can use break with label.

Here is example from Java tutorial: search is label here.

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");
        }
    }
}
kosa
  • 65,990
  • 13
  • 130
  • 167
0

Use the 'break' statement at the end of your if block. This will skip the remaining iterations of the "j" loop, and the next iteration of the "i" loop will run.

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;
      }
   }
}
davidfg4
  • 476
  • 3
  • 9