THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

}


To terminate an outer loop or block, you label the outer statement and use its label name in the break
statement:


private float[][] matrix;


public boolean workOnFlag(float flag) {
int y, x;
boolean found = false;


search:
for (y = 0; y < matrix.length; y++) {
for (x = 0; x < matrix[y].length; x++) {
if (matrix[y][x] == flag) {
found = true;
break search;
}
}
}
if (!found)
return false;


// do some stuff with flagged value at matrix[y][x]
return true;
}


Here we label the outer for loop and if we find the value we are looking for, we terminate both inner and
outer loops by using a labeled break. This simplifies the logic of the loops because we do not need to add a
!found clause in the loop expressions.


Note that a labeled break is not a goto. The goto statement would enable indiscriminate jumping around
in code, obfuscating the flow of control. A break or continue that references a label, on the other hand,
exits from or repeats only that specific labeled block, and the flow of control is obvious by inspection. For
example, here is a modified version of workOnFlag that labels a block instead of a loop, allowing us to
dispense with the found flag altogether:


public boolean workOnFlag(float flag) {
int y, x;


search:
{
for (y = 0; y < matrix.length; y++) {
for (x = 0; x < matrix[y].length; x++) {
if (matrix[y][x] == flag)
break search;
}
}


// if we get here we didn't find it
return false;
}
// do some stuff with flagged value at matrix[y][x]
return true;
}

Free download pdf