Java Reference
In-Depth Information
Suppose that you want to write each number on a line by itself. In that case, you
can use a for-each loop that does a println for each value:
public static void print(int[] list) {
for (int n : list) {
System.out.println(n);
}
}
You can then call this method with the variable list :
print(list);
This call produces the following output:
17
-3
42
8
12
2
103
In some cases, the for-each loop doesn't get you quite what you want, though. For
example, consider how the Arrays.toString method must be written. It produces a
list of values that are separated by commas, which is a classic fencepost problem
(e.g., seven values separated by six commas). To solve the fencepost problem, you'd
want to use an indexing loop instead of a for-each loop so that you can print the first
value before the loop:
System.out.print(list[0]);
for (int i = 1; i < list.length; i++) {
System.out.print(", " + list[i]);
}
System.out.println();
Notice that i is initialized to 1 instead of 0 because list[0] is printed before the
loop. This code produces the following output for the preceding sample array:
17, -3, 42, 8, 12, 2, 103
Even this code is not correct, though, because it assumes that there is a list[0]
to print. It is possible for arrays to be empty, with a length of 0, in which case
this code will generate an ArrayIndexOutOfBoundsException . The version of the
method that follows produces output that matches the String produced by
 
Search WWH ::




Custom Search