Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 5 ■ CONTROL FLOW, LOOPING, AND BRANCHING


Listing 5-9. Modifying the initialization variable in the loop body

int[] compassPoints = {22, 77, 144, 288};
for (int i = 0; i < compassPoints.length; i++) {
System.out.println(compassPoints[i++] + " degrees is (very roughly) " +
Direction.findCardinalDirection(compassPoints[i]));
}

Notice that we add a postfix operator to the initialization variable at one point where it's used as an
index. Consequently, this loop now processes items 0 and 2 in the compassPoints array. As you can see,
this offers another way to process every other item. If we make i++ be i += 2, the loop processes every
third item and processes items 0 and 3. Although potentially useful, this kind of thing can lead to
problems. Again, test thoroughly.
By the way, the best practice for processing alternating items differently is not to write two for loops
or do math on the increment value but to test each item as it goes through the loop and do the
appropriate thing in each case, as shown in Listing 5-10.

Listing 5-10. Processing every other item in a single loop

int[] compassPoints = {22, 77, 144, 288};
for (int i = 0; i < compassPoints.length; i++) {
if (i % 2 == 1) {
System.out.println("[" + i + " is odd] " + compassPoints[i] +
" degrees is (very roughly) " +
Direction.findCardinalDirection(compassPoints[i]));
} else {
System.out.println("[" + i + " is even] " + compassPoints[i] +
" degrees is (very roughly) " +
Direction.findCardinalDirection(compassPoints[i]));
}
}

Listing 5-11 shows the output of that loop.

Listing 5-11. Output from processing alternate items differently

[0 is even] 22 degrees is (very roughly) NORTH
[1 is odd] 77 degrees is (very roughly) EAST
[2 is even] 144 degrees is (very roughly) SOUTH
[3 is odd] 288 degrees is (very roughly) WEST

This kind of code is often used to alternate the colors of rows in tables and similar applications.
Using if (i % 3 == 1) processes every third item differently, and so on.
for loops support an alternate (and sometimes handy) syntax, called enhanced for syntax. The
enhanced for syntax consists of an initialization variable and an object (an array in this case) to associate
with the initialization variable. Every item in the object gets processed by the loop, with the initialization
variable providing access to the current index value (which is nearly always needed). Provided you want
to process every item (though you can skip items with if statements in the loop body), the enhanced for
syntax provides a nice shortcut. The enhanced for syntax was created for collections and arrays, but it
can also be used with enumerations (as we saw in Chapter 3, “Operators”). Let's consider an example in
Listing 5-12, using the same array that we saw in the previous examples.
Free download pdf