0
public class Newfile{
     public static void main(String []args){
         for(int a=1; a < 5; a++){
             for(int b=1; b < 5; b++){
                 if(a == b){
                     System.out.println("pair found   " + a + "    " + b);
                     break;
                  }
              }  
          } 
     }
}

This code just breaks the inner most loop, so it breaks the loop with the b but not the a loop, I am doing this as an exercise.

I was wondering, is there a way to break BOTH loops once a == b is satisfied?

SujitKumar
  • 142
  • 1
  • 10
Amad27
  • 151
  • 1
  • 1
  • 8
  • 1
    http://stackoverflow.com/questions/886955/breaking-out-of-nested-loops-in-java?rq=1 this can help – Viet Jan 11 '17 at 07:26

2 Answers2

1

One alternative to using labels would be to assign values to the loop counters from all loops involved such that both loop conditions would fail, upon hitting a certain state or condition.

        for (int a=1; a < 5; a++) {
            for (int b=1; b < 5; b++) {
                if (a == b) {
                    System.out.println("pair found   " + a + "    " + b);
                    b = 5;
                    a = 5;
               }
           }
       }
jack jay
  • 2,493
  • 1
  • 14
  • 27
  • Using labels reduce your code :) – Suresh Atta Jan 11 '17 at 07:30
  • @Tim Biegeleisen Thanks. – jack jay Jan 11 '17 at 07:37
  • This would definitely work, but you would lose the value of `a` and `b` when the condition was met. This becomes relevant in cases when you need to use those values of `a` or `b`. For ex, at what position `[i][j]` in a 2-d array, the value is negative. – Saurav Sahu Jan 11 '17 at 08:45
  • `a` and `b` are initialized inside `for loop` so you cant access them outside. If at all position is required it can be stored somewhere else before breaking from loop or include some other variable for breaking form loop and declare `a` and `b` outside the loop. – jack jay Jan 11 '17 at 08:52
1

Just use a flag to break out of both loops:

boolean breakAll = false;   // <<<< flag for breaking out
for(int a=1; a < 5 && !breakAll; a++){
    for(int b=1; b < 5 && !breakAll; b++){
       if(a == b){
            System.out.println("pair found   " + a + "    " + b);
            breakAll = true;
       }
    }
}
Kevyn Meganck
  • 609
  • 6
  • 15
Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79