Break-continue without auxiliary boolean variable?
Question
In Java, I have such code:
boolean contains;
for (int i = 0; i < n; i++) {
// get the current matrix value
t = A[i][j];
// check if it has been already considered
contains = false;
for (int z = 0; z < l; z++) {
if (arrays[z].contains(t)) {
contains = true; break;
}
}
if (contains) continue;
...
}
Is it possible to use label then jump out of the inner loop and do continue without a boolean variable contains
?
I need to do break-continue and not break from all loops.
Solution
outerLoop:
for (int i = 0; i < n; i++) {
// get the current matrix value
t = A[[i]][j];
// check if it has been already considered
for (int z = 0; z < l; z++) {
if (arrays[z].contains(t)) {
continue outerLoop;
}
}
}
OTHER TIPS
Using labes leads to spaghetti code making your code less readable.
You could extract the inner for-loop in its own method returning a boolean:
private boolean contains(/* params */) {
for (int z = 0; z < l; z++) {
if (arrays[z].contains(t)) {
return true;
}
}
}
and use it in the outer for-loop
for (int i = 0; i < n; i++) {
// get the current matrix value
t = A[[i]][j];
// check if it has been already considered
if (contains(/*params*/))
continue;
...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow