Java Reference
In-Depth Information
order). For example, to set the fourth value of the first row to 98.3 and to set the first
value of the third row to 99.4 , you would write the following code:
temps[0][3] = 98.3; // fourth value of first row
temps[2][0] = 99.4; // first value of third row
After the program executes these lines of code, the array would look like this:
[0]
[1]
[2]
[3]
[4]
[0]
0.0
0.0
0.0
98.3
3
0.0
temps
[1]
0.0
0.0
0.0
0.0
0.0
[2]
99.4 0.0
3
0.0
0.0
0.0
It is helpful to think of referring to individual elements in a stepwise fashion, start-
ing with the name of the array. For example, if you want to refer to the first value of
the third row, you obtain it through the following steps:
temps the entire grid
temps[2] the entire third row
temps[2][0] the first element of the third row
You can pass multidimensional arrays as parameters just as you pass one-dimensional
arrays. You need to be careful about the type, though. To pass the temperature grid, you
would have to use a parameter of type double[][] (with both sets of brackets). For
example, here is a method that prints the grid:
public static void print(double[][] grid) {
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println();
}
}
Notice that to ask for the number of rows you ask for grid.length and to ask for
the number of columns you ask for grid[i].length .
The Arrays.toString method mentioned earlier in this chapter does work on
multidimensional arrays, but it produces a poor result. When used with the preceding
array temps , it produces output such as the following:
[[D@14b081b, [D@1015a9e, [D@1e45a5c]
This poor output is because Arrays.toString works by concatenating the
String representations of the array's elements. In this case the elements are arrays
themselves, so they do not convert into String s properly. To correct the problem you
can use a different method called Arrays.deepToString that will return better
results for multidimensional arrays:
System.out.println(Arrays.deepToString(temps));
 
Search WWH ::




Custom Search