Java Reference
In-Depth Information
Listing 5-7. Loop that finds directions
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]));
}
The for loop consists of two parts: the information that controls the looping and the block of code
that gets run each time through the loop. The control section (within the parentheses) consists of three
parts: initialization, termination, and increment. Each of these three parts ends with a semicolon,
though the semicolon after the increment is often dropped. The names give us a good indication of what
they do. The initialization code sets up whatever variable we use for our counting, the termination code
indicates how to know when to stop looping, and the increment code dictates how to change the
initialization variable each time through the loop. In this simple case, we set an int named i to 0,
running the code in the loop for each item in the compassPoints array, and incrementing the
initialization variable ( i ) by one each time.
Java programmers can certainly do things differently than shown here. Consider the following for
statements in Listing 5-8.
Listing 5-8. Alternate for loops
// Process just half the compassPoints array
for (int i = compassPoints.length / 2; i < compassPoints.length; i++) {
}
// Process every other member of the compassPoints array
for (int i = 0; i < compassPoints.length; i += 2) {
}
The first of the two loops process the high-value half (items 2 and 3—remember that arrays start at
0) of the compassPoints array. The second loop processes items 0 and 2. If we use int i = 1 , the second
loop processes items 1 and 3. As a rule, any variable that can be counted (including char variables, but
that's bad practice unless you process individual characters—otherwise, groups of characters should be
treated as String objects, both for simplicity and for performance) can serve as the initialization value,
and it can start at any of the variable's possible values (including negative numbers). Also, any valid
mathematical operation can be performed in the increment value. Of course, if you also use the
initialization variable as an index into an array, using a negative number gets you an ArrayOutOfBounds
exception, because array indices don't use negative numbers. When you do these kinds of things,
though, test thoroughly to be sure you get the results you expect.
Speaking of using the initialization variable as an index, that's exactly what we do in Listing 5-7. You
can also perform mathematical operations on the initialization variable in the body of the loop, as
shown in Listing 5-9.
Search WWH ::




Custom Search