My WarGame.java program required me to break out of two loops if a certain condition came up. Many programmers would say that you should fix your logic if you’re going to need to break out of two loops, but in this particular case, the solution seemed to be just that.
In java, you’re offered the ability to name (or label) your loop structures. Oddly enough there is a secret that mostly goes untold except on remote Internet forums: the secret of break.
The break keyword in java is a flow manipulator and coupled with loop labeling, you can break out of any number of loops simply using the name of the loop you wish to break out of.
import java.util.*;
class LabelLoop {
public static void main(String[] args) {
firstforloop: for (int i = 0; i < 10; i++) {
secondforloop: for (int j = 0; j < 10; j++) {
if ( i == 7 && j == 9 ) {
System.out.println("Breaking out now!");
break firstforloop;
}
}
}
}
}
The example above uses two for loops and an if statement dependent on the loop variables of i and j to trigger the break out. The example names both loops however if you only wanted to break out of the outer loop, you only actually need to name the outer loop.
As always, be careful when using control structure manipulators because they make spaghetti code really fast.
thanks for this java reminder..