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?

1

2 Answers 2

2

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;
       }
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This would work in case of xml readers too. A nice generic solution.
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;
               }
           }
       }

4 Comments

Using labels reduce your code :)
@Tim Biegeleisen Thanks.
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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.