Java Reference
In-Depth Information
name. For example, the following method will display a two-dimensional array in the
usual way as rows and columns:
6
public static void
showMatrix(
int
[][] a)
{
int
row, column;
for
(row = 0; row < a.length; row++)
{
for
(column = 0; column < a[row].length; column++)
System.out.print(a[row][column] + " ");
System.out.println();
}
}
If you want to return a multidimensional array, you use the same kind of type
specification as you use for a multidimensional array parameter. For example, the
following method returns a two-dimensional array with base type
double
:
returning an
array
/**
Precondition: Each dimension of a is at least the value of size.
The array returned is the same as the size-by-size upper upper-
left corner of the array a.
*/
public static double
[][] corner(
double
[][] a,
int
size)
{
double
[][] temp =
new double
[size][size];
int
row, column;
for
(row = 0; row < size; row++)
for
(column = 0; column < size; column++)
temp[row][column] = a[row][column];
return
temp;
}
EXAMPLE:
A Grade Book Class
Display 6.18 contains a class for grade records in a class whose only recorded scores
are quiz scores. An object of this class has three array instance variables. One is a two-
dimensional array named
grade
that records the grade of each student on each quiz.
For example, the score that student number
4
received on quiz number
1
is recorded
in
grade[3][0]
. Because the student numbers and quiz numbers start with
1
and the
array indices start with
0
, we subtract one from the student number or quiz number
to obtain the corresponding array index.
6
It is worth noting that this method works fine for ragged arrays.