Java Reference
In-Depth Information
able followed by the current index enclosed in brackets (often called an array sub-
script):
// From the meanGrade() method:
for (int i = 0; i < _grades.length; i++) {
sum += _grades[i];
}
Alternatively, the enhanced
for
loop, also known as the
foreach
loop, could be
used to iterate over the array (see Recipe 7-7 for more discussion of the
foreach
loop):
for (int grade : _grades) {
sum += grade;
}
Notice that to determine the min and max grade, the grades are first sorted in their
natural (ascending) order using the utility
sort
method from the
java.util.Arrays
class. After sorting, the min grade is the simply the first ele-
ment (at index
0
) of the array, and the max grade is the last element (at index
length
-1
) of the array.
The three static class methods in the solution,
initGrades1()
,
initGrades2()
, and
initGrades3()
, demonstrate three different ways of creat-
ing and initializing the array data you will use to “seed” the
GradeAnalyzer
. The
initGrades1()
method declares and creates an array (using
new
) that can hold
five grades, then manually sets the value at each element index to an integer grade
value. The
initGrades2()
method combines array creation and initialization in
one line using the special array initializer syntax:
int[] grades = { 57, 88, 67, 95, 99, 74, 81 };
This syntax creates an array with a length of
7
and initializes the elements from in-
dex
0
through index
6
with the integer values shown. Note that this syntax can be used
only in an array declaration, so the following is not allowed:
int[] grades;
grades = { 57, 88, 67, 95, 99, 74, 81 }; // won't compile