4

In Java, what is the direct method of getting out of a WHILE loop which is inside a WHILE loop and which is inside a FOR loop? The structure should look something like this:

For{
.
.
   While{
   .
   .
   .
     While{
     .
     .
     <Stuck here. Want to break Free of all Loops>;
     }
   }
}
Kick Buttowski
  • 6,631
  • 13
  • 35
  • 57
Shubhankar Raj
  • 311
  • 1
  • 10

2 Answers2

3

use a label and a break

here:

    while (...) {
       for (...) {

         if (...) break here;
       }
   }

see https://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html

Kick Buttowski
  • 6,631
  • 13
  • 35
  • 57
Scary Wombat
  • 43,525
  • 5
  • 33
  • 63
3

Want to break Free of all Loops

You can use a plain break; to end the immediate containing loop and in Java you can use labeled break to end an arbitrary loop. Like

out: for(;;) {
    while(true) {
        while (true) {
            // ....
            break out;
        }
    }
 }

The label is the text before : (and the word after break in the example above).

Note:An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement.

Source of the Note

Kick Buttowski
  • 6,631
  • 13
  • 35
  • 57
Elliott Frisch
  • 191,680
  • 20
  • 149
  • 239