-1

I want to exit from two for loops when count become 9. I use break for that but it can exit from only the first for loop. How can it done?

       ArrayList<String> list = new ArrayList<String>();
        int count = 0;
        System.out.println("Before entering to loop");
        for(int i=0;i<5;i++){
            list.add("XYZ"+i);
            for( int j=0;j<5;j++){
                list.add("ABC"+j);
                count++;
                if(count==9){
                    System.out.println("I want to exit from here.");
                    break;
                }
                System.out.println("i="+i+"::j="+j);
            }
            System.out.println("------------");
        }
        for(String str:list){
            System.out.println(str);
        }
    }
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
  • possible duplicate of [How to Break from main/outer loop in a double/nested loop?](http://stackoverflow.com/questions/13073300/how-to-break-from-main-outer-loop-in-a-double-nested-loop) โ€“ Rohit Jain Aug 26 '13 at 14:04

7 Answers7

6

You can use labels:

OUTER: for (...) {  // <--
    ...
    for (...) {
        if (...)
            break OUTER;  // <--
    }
}

This is covered in the Branching Statements section of the Java tutorial and in JLS ยง14.7.

arshajii
  • 127,459
  • 24
  • 238
  • 287
  • 1
    Take care, it may reduce your code to a plate of spaghetti. You may prefer having your loops in a specific method that could return some value when done. Or refactor your algorithm to have only one loop. โ€“ Guillaume Aug 26 '13 at 14:08
1

You can go for Labels

Label:

You can put a label at the start of a loop. A label is an identifier, followed by a colon. It's just a location in your code. You can then use break followed by the label name to break out of the loop with the label by it.

For Example :

public void twoNum( int num, int val )
{
OUTER_LOOP: // OUTER_LOOP is a label
  for ( int i = 0 ; i < num ; i++ )
  {
      for ( int j = 0 ; j < num ; j++ )
      {
         if ( i + j >= 2 * val )
            break OUTER_LOOP ;
         val = val / 2 ;
      }
  }
  // break comes here if it runs

Incremental java

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Before you break out of the inner loop you could set a boolean flag to true. Then check in the outer loop if it's true. If that's the case, break out of the outer loop as well.

RaptorDotCpp
  • 1,425
  • 14
  • 26
  • 2
    (or) you can use labeled break http://stackoverflow.com/questions/15481/java-coding-standard-best-practices-labeled-break-continue โ€“ kosa Aug 26 '13 at 14:01
0

You can introduce a flag, which is set in the inner loop when the count reaches 9. And outer loop will have an if statement to check that flag value. If true, break the outer loop as well. Something like this:

boolean breakLoop = false;
for(int i=0;i<5;i++){
            list.add("XYZ"+i);
            for( int j=0;j<5;j++){
                list.add("ABC"+j);
                count++;
                if(count==9){
                    System.out.println("I want to exit from here.");
                    breakLoop = true;
                    break;
                }
                System.out.println("i="+i+"::j="+j);
            }
             if(breakLoop)
                 break;
            System.out.println("------------");
        }
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
0
 boolean outer=false;
 for(int i=0;i<5;i++){
        list.add("XYZ"+i);
        for( int j=0;j<5;j++){
            list.add("ABC"+j);
            count++;
            if(count==9){
                outer= true;
                System.out.println("I want to exit from here.");
                break;
            }
            System.out.println("i="+i+"::j="+j);
        }
        System.out.println("------------");
        if(outer==true)
        break;
    }
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64
0

There are a lot of answers regarding break statements and labels, but these constructs generally lead to messy code that's hard to understand when reading for the first time (or re-reading after a while). Generally I think you're better off refactoring in a case like this.

In your example, you know you want to stop after 9 iterations of the inner loop, so why are you bothering to set your loop counters to 5? It would be more clear to explicitly do what you want:

    ArrayList<String> list = new ArrayList<String>();

    System.out.println("Before entering to loop");
    list.add("XYZ"+i);
    for( int j=0;j<5;j++){
      list.add("ABC"+j);
    }
    list.add("XYZ"+i);
    for( int j=0;j<4;j++){
      list.add("ABC"+j);
    }
    for(String str:list){
        System.out.println(str);
    }
}

Look how much we were able to eliminate, and the resulting code more clearly demonstrates what it's going to do. I understand that this may have just been an illustrative example, but I think the point still stands - it's likely the case that in your real-world code there's an analogous chance for refactoring.

danben
  • 80,905
  • 18
  • 123
  • 145
0

Just add the

(count!=9)

condition to the for loops:

   ArrayList<String> list = new ArrayList<String>();
    int count = 0;
    System.out.println("Before entering to loop");
    for(int i=0;i<5;i++){
        list.add("XYZ"+i);
        for( int j=0;j<5 && count!=9;j++){
            list.add("ABC"+j);
            count++;
            System.out.println("i="+i+"::j="+j);
        }
        System.out.println("------------");
    }
    for(String str:list){
        System.out.println(str);
    }
Marco
  • 129
  • 1
  • 1
  • 9