Java Reference
In-Depth Information
97
98
99
100
101
102 // for each grade frequency, print bar in chart
103 for ( int count = 0 ; count < frequency.length; count++)
104 {
105 // output bar label ("00-09: ", ..., "90-99: ", "100: ")
106 if (count == 10 )
107 System.out.printf( "%5d: " , 100 );
108 else
109 System.out.printf( "%02d-%02d: " ,
110 count * 10 , count * 10 + 9 );
111
112 // print bar of asterisks
113 for ( int stars = 0 ; stars < frequency[count]; stars++)
114 System.out.print( "*" );
115
116 System.out.println();
117 }
118 }
119
120 // output the contents of the grades array
121 public void outputGrades()
122 {
123 System.out.printf( "The grades are:%n%n" );
124
125 // output each student's grade
126
127
// for each grade, increment the appropriate frequency
for ( int grade : grades)
++frequency[grade / 10 ];
for ( int student = 0 ; student < grades.length; student++)
System.out.printf( "Student %2d: %3d%n" ,
student + 1, grades[student]);
128
129 }
130 } // end class GradeBook
Fig. 7.14 | GradeBook class using an array to store test grades. (Part 3 of 3.)
Method processGrades (lines 29-43) contains a series of method calls that output a
report summarizing the grades. Line 32 calls method outputGrades to print the contents
of the array grades . Lines 126-128 in method outputGrades output the students' grades.
A counter-controlled for statement must be used in this case, because lines 127-128 use
counter variable student 's value to output each grade next to a particular student number
(see the output in Fig. 7.15). Although array indices start at 0, a professor might typically
number students starting at 1. Thus, lines 127-128 output student + 1 as the student
number to produce grade labels "Student 1: " , "Student 2: " , and so on.
Method processGrades next calls method getAverage (line 35) to obtain the average
of the grades in the array. Method getAverage (lines 78-88) uses an enhanced for state-
ment to total the values in array grades before calculating the average. The parameter in
the enhanced for 's header (e.g., int grade ) indicates that for each iteration, the int vari-
able grade takes on a value in the array grades . The averaging calculation in line 87 uses
grades.length to determine the number of grades being averaged.
Search WWH ::




Custom Search