0 votes
1 view
in Java by (3.5k points)

I’ve created this nested loop:

for (Type type : types) {

   for (Type t : types2) {

        if (some condition) {

            // Do something and break...

            break; // Breaks out of the inner loop

        }

   }

}

I want to break out of both loops, How can I do that?  I've also read the other answers but I can't apply them as most of them used gotos.

I also don't wanna put the inner loop in a different method.

I don't want to rerun the loops. When breaking I'm concluded with the execution of the loop block.

1 Answer

0 votes
by (46.1k points)

To perform this task use break with a label for the outer loop.

In the example below, we have two loops, Outer loop, and Inner Loop. We are printing numbers in both the loop but as the product of two counters exceeds 5, we break the outer loop.

Example:

Input:

import java.io.IOException;

public class BreakingFromNestedLoop{

   public static void main(String args[]) throws IOException

{

       // this is our outer loop

       outer: (int i = 0; i < 4; i++)

{

           // this is the inner loop

           (int j = 0; j < 4; j++)

{

            // condition to break from the nested loop

               if (i * j > 5)

{

                   System.out.println("Breaking from nested loop");

                   break outer;

               }

               System.out.println(i + " " + j);

           }

       }

       System.out.println("exited");

Output:

0 0

0 1

0 2

0 3

1 0

1 1

1 2

1 3

2 0

2 1

2 2

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...