0

I want to exit inner loop and to pass outer loop with +1.

Example:

public class MyClass {
    public static void main(String args[]) {
        for(int i=0; i<10; i++){
            System.out.println("Outer loop : "+ i);
            for (int j=0; j<10; j ++){
                if(j == 3){
                    System.out.println("<-- Break Inner loop--> on j == "+j);
                    break; 
                }               
            }
            System.out.println("This code is executing but I do not want if break executes");
        }
    }
}
samabcde
  • 6,988
  • 2
  • 25
  • 41
tom
  • 215
  • 3
  • 11
  • 2
    "_I want that it should exit from inner loop and increase outer loop +1_" - that's exactly what it is doing – Martin Jul 30 '21 at 12:45
  • For example: if i=0 and j=3 break statement exeutes i=0 is still but I want break statement execution is okey but i should be 1 and outer loop should start again. – tom Jul 30 '21 at 12:48
  • @samabcde I do not want finish outer loop but only to pass next "i" – tom Jul 30 '21 at 12:50
  • Not sure what is trying to be achieved, but you could do `i++;` before the `break;`? Though that seems to be an odd thing to do for the flow of the loops, could cause other issues depending on the handling. – Paul T. Jul 30 '21 at 12:52
  • @tom, may be you can give an example assuming `i` is 1 before the inner loop, and what you expect `i` after breaking inner loop. – samabcde Jul 30 '21 at 12:58
  • Break will not exit outer loop, It's breaking the inner loop and incrementing the outer ```i``` [code](https://jdoodle.com/ia/fuj). You need to be clear with the problem statement. – Abhi Jul 30 '21 at 12:58
  • 1
    I edited my question by using @samabcde code – tom Jul 30 '21 at 13:21
  • This is much more clear. One simple way is to add a boolean flag with `false` in the outer loop, and change it to `true` when inner loop break. Then you can skip executing the code when the flag is `true`. – samabcde Jul 30 '21 at 13:51
  • You can used a labeled `continue` if you need to. If you add `outer:` on the line before the outer loop, you can use `continue outer;` instead of `break` and it'll break out of the inner loop and start the next iteration of the outer loop. I don't personally recommend this style, but it'll do what you're looking for I think. – Marc Baumbach Jul 30 '21 at 14:09

0 Answers0