Java Reference
In-Depth Information
for
(
int
column =
0
; column < a[
2
].length; column++)
a[
2
][column] =
0
;
We specified row
2
; therefore, we know that the
first
index is always
2
(
0
is the first row,
and
1
is the second row). This
for
loop varies only the
second
index (i.e., the column in-
dex). If row
2
of array
a
contains four elements, then the preceding
for
statement is equiv-
alent to the assignment statements
a[
2
][
0
] =
0
;
a[
2
][
1
] =
0
;
a[
2
][
2
] =
0
;
a[
2
][
3
] =
0
;
The following nested
for
statement totals the values of all the elements in array
a
:
int
total =
0
;
for
(
int
row =
0
; row < a.length; row++)
{
for
(
int
column =
0
; column < a[row].length; column++)
total += a[row][column];
}
These nested
for
statements total the array elements
one row at a time
. The outer
for
state-
ment begins by setting the
row
index to
0
so that the first row's elements can be totaled by
the inner
for
statement. The outer
for
then increments
row
to
1
so that the second row
can be totaled. Then, the outer
for
increments
row
to
2
so that the third row can be to-
taled. The variable
total
can be displayed when the outer
for
statement terminates. In
the next example, we show how to process a two-dimensional array in a similar manner
using nested enhanced
for
statements.
Dimensional Array
In Section 7.10, we presented class
GradeBook
(Fig. 7.14), which used a one-dimensional
array to store student grades on a single exam. In most semesters, students take several ex-
ams. Professors are likely to want to analyze grades across the entire semester, both for a
single student and for the class as a whole.
Storing Student Grades in a Two-Dimensional Array in Class
GradeBook
Figure 7.18 contains a
GradeBook
class that uses a two-dimensional array
grades
to store
the grades of
several
students on
multiple
exams. Each
row
of the array represents a
single
student's grades for the entire course, and each
column
represents the grades of
all
the stu-
dents who took a particular exam. Class
GradeBookTest
(Fig. 7.19) passes the array as an
argument to the
GradeBook
constructor. In this example, we use a ten-by-three array for ten
students' grades on three exams. Five methods perform array manipulations to process the
grades. Each method is similar to its counterpart in the earlier one-dimensional array ver-
sion of
GradeBook
(Fig. 7.14). Method
getMinimum
(lines 46-62) determines the lowest
grade of any student for the semester. Method
getMaximum
(lines 65-83) determines the
highest grade of any student for the semester. Method
getAverage
(lines 86-96) deter-
mines a particular student's semester average. Method
outputBarChart
(lines 99-129) out-