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,709
  • 13
  • 37
  • 58
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,709
  • 13
  • 37
  • 58
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
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,709
  • 13
  • 37
  • 58
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249