Java Reference
In-Depth Information
101
System.out.println(
"Overall grade distribution:"
);
102
103
// stores frequency of grades in each range of 10 grades
104
int
[] frequency =
new
int
[
11
];
105
106
107
108
109
110
111
112
113
// for each grade frequency, print bar in chart
114
for
(
int
count =
0
; count < frequency.length; count++)
115
{
116
// output bar label ("00-09: ", ..., "90-99: ", "100: ")
117
if
(count ==
10
)
118
System.out.printf(
"%5d: "
,
100
);
119
else
120
System.out.printf(
"%02d-%02d: "
,
121
count *
10
, count *
10
+
9
);
122
123
// print bar of asterisks
124
for
(
int
stars =
0
; stars < frequency[count]; stars++)
125
System.out.print(
"*"
);
126
127
System.out.println();
128
}
129
}
130
131
// output the contents of the grades array
132
public
void
outputGrades()
133
{
134
System.out.printf(
"The grades are:%n%n"
);
135
System.out.print(
" "
);
// align column heads
136
137
// create a column heading for each of the tests
138
for
(
int
test =
0
; test < grades[
0
].length; test++)
139
System.out.printf(
"Test %d "
, test + 1);
140
141
System.out.println(
"Average"
);
// student average column heading
142
143
// create rows/columns of text representing array grades
144
for
(
int
student =
0
; student < grades.length; student++)
145
{
146
System.out.printf(
"Student %2d"
, student + 1);
147
148
for
(
int
test : grades[student])
// output student's grades
149
System.out.printf(
"%8d"
, test);
150
151
// call method getAverage to calculate student's average grade;
152
// pass row of grades as the argument to getAverage
153
// for each grade in GradeBook, increment the appropriate frequency
for
(
int
[] studentGrades : grades)
{
for
(
int
grade : studentGrades)
++frequency[grade /
10
];
}
double
average = getAverage(grades[student]);
Fig. 7.18
|
GradeBook
class using a two-dimensional array to store grades. (Part 3 of 4.)