Hi
I am beginner in java and my program has 4 for loops:
my program works like this that if b
is true
,the element will be removed from pointList and n
will be n--
and the I want to go out from all for loops and come again from the first for loop so l
will be l++
,how can i do this ? with break statement?
for (int l = 0; l < n; l++) {
for (int i = 1; i < (n - 2); i++) {
for (int j = i + 1; j < (n - 1); j++) {
for (int k = j + 1; k < n; k++) {
if (l != i && l != j && l != k) {
boolean b = isOK(pointList.get(l), pointList.get(i), pointList.get(j), pointList.get(k));
System.out.println(b);
if (b == true) {
pointList.remove(pointList.get(l);
n--;
break;
}
else
System.out.println(b);
}
}
}
}
}
You can make use of a labeled break as:
for (int l = 0; l < n; l++) {
foo: for (int i = 1; i < (n - 2); i++) {
for (int j = i + 1; j < (n - 1); j++) {
for (int k = j + 1; k < n; k++) {
if (l != i && l != j && l != k) {
boolean b = isOK(pointList.get(l), pointList.get(i), pointList.get(j), pointList.get(k));
System.out.println(b);
if (b == true) {
pointList.remove(pointList.get(l);
n--;
break foo;
}
else
System.out.println(b);
}
}
}
}
}
In a loop the break
statement terminates the inner loop while continue
skips to the next iteration. In order for these two statements to work on a different loop to the inner one you need to use labels. Something like this should work:
outerloop:
for (int l = 0; l < n; l++) {
for (int i = 1; i < (n - 2); i++) {
for (int j = i + 1; j < (n - 1); j++) {
for (int k = j + 1; k < n; k++) {
if (l != i && l != j && l != k) {
boolean b = isOK(pointList.get(l), pointList.get(i), pointList.get(j), pointList.get(k));
System.out.println(b);
if (b == true) {
pointList.remove(pointList.get(l);
n--;
continue outerloop;
}
else
System.out.println(b);
}
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With