I\'ve got a nested loop construct like this:
for (Type type : types) {
for (Type t : types2) {
if (some condition) {
// Do somethin
Even creating a flag for the outer loop and checking that after each execution of the inner loop can be the answer.
Like this:
for (Type type : types) {
boolean flag=false;
for (Type t : types2) {
if (some condition) {
// Do something and break...
flag=true;
break; // Breaks out of the inner loop
}
}
if(flag)
break;
}
You can use a named block around the loops:
search: {
for (Type type : types) {
for (Type t : types2) {
if (some condition) {
// Do something and break...
break search;
}
}
}
}
boolean broken = false; // declared outside of the loop for efficiency
for (Type type : types) {
for (Type t : types2) {
if (some condition) {
broken = true;
break;
}
}
if (broken) {
break;
}
}
I needed to do a similar thing, but I chose not to use the enhanced for loop to do it.
int s = type.size();
for (int i = 0; i < s; i++) {
for (int j = 0; j < t.size(); j++) {
if (condition) {
// do stuff after which you want
// to completely break out of both loops
s = 0; // enables the _main_ loop to terminate
break;
}
}
}
You can use labels:
label1:
for (int i = 0;;) {
for (int g = 0;;) {
break label1;
}
}
You can break from all loops without using any label: and flags.
It's just tricky solution.
Here condition1 is the condition which is used to break from loop K and J. And condition2 is the condition which is used to break from loop K , J and I.
For example:
public class BreakTesting {
public static void main(String[] args) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
for (int k = 0; k < 9; k++) {
if (condition1) {
System.out.println("Breaking from Loop K and J");
k = 9;
j = 9;
}
if (condition2) {
System.out.println("Breaking from Loop K, J and I");
k = 9;
j = 9;
i = 9;
}
}
}
}
System.out.println("End of I , J , K");
}
}