Java Reference
In-Depth Information
grades. The GradeBook classes later in the chapter (Figs. 7.14 and 7.18) contain code that
calculates these grade frequencies based on a set of grades. For now, we manually create
the array with the given grade frequencies.
1
// Fig. 7.6: BarChart.java
2
// Bar chart printing program.
3
4
public class BarChart
5
{
6
public static void main(String[] args)
7
{
8
int [] array = { 0 , 0 , 0 , 0 , 0 , 0 , 1 , 2 , 4 , 2 , 1 };
9
10
System.out.println( "Grade distribution:" );
11
12
// for each array element, output a bar of the chart
13
for ( int counter = 0 ; counter < array.length; counter++)
14
{
15
// output bar label ("00-09: ", ..., "90-99: ", "100: ")
16
if (counter == 10 )
17
System.out.printf( "%5d: " , 100 );
18
else
19
System.out.printf( "%02d-%02d: " ,
20
counter * 10 , counter * 10 + 9 );
21
22
// print bar of asterisks
for ( int stars = 0 ; stars < array[counter]; stars++)
System.out.print( "*" );
23
24
25
26
System.out.println();
27
}
28
}
29
} // end class BarChart
Grade distribution:
00-09:
10-19:
20-29:
30-39:
40-49:
50-59:
60-69: *
70-79: **
80-89: ****
90-99: **
100: *
Fig. 7.6 | Bar chart printing program.
The application reads the numbers from the array and graphs the information as a bar
chart. It displays each grade range followed by a bar of asterisks indicating the number of
grades in that range. To label each bar, lines 16-20 output a grade range (e.g., "70-79: " )
based on the current value of counter . When counter is 10 , line 17 outputs 100 with a
 
Search WWH ::




Custom Search