import java.awt.Graphics;
import javax.swing.JApplet;
import javax.swing.JOptionPane;
public class GradeBookApplet extends JApplet
{
// initialization phase
private int total = 0;
private int gradeCounter = 0;
private double classAverage;
private int gradeFrequency [] = new int [11];
public void init()
{
String gradeString = JOptionPane.showInputDialog("Enter a grade or -1 to quit");
// convert grade to integer
int grade = Integer.parseInt(gradeString);
// loop until sentinel value read from user
while ( grade != -1)
{
total += grade;
++gradeCounter;
if (grade < 10)
++gradeFrequency[0];
else if (grade < 20)
++gradeFrequency[1];
else if (grade < 30)
++gradeFrequency[2];
else if (grade < 40)
++gradeFrequency[3];
else if (grade < 50)
++gradeFrequency[4];
else if (grade < 60)
++gradeFrequency[5];
else if (grade < 70)
++gradeFrequency[6];
else if (grade < 80)
++gradeFrequency[7];
else if (grade < 90)
++gradeFrequency[8];
else if (grade < 100)
++gradeFrequency[9];
else if (grade == 100)
++gradeFrequency[10];
gradeString = JOptionPane.showInputDialog("Enter a grade or -1 to quit");
// convert grade to integer
grade = Integer.parseInt(gradeString);
}
}
public void paint (Graphics g)
{
// call superclass version of method paint
super.paint(g);
// draw a string
g.drawString("GRADES DISTRIBUTION FOR THE CLASS:",25,25);
// for each array element output bar for chart
for (int counter = 0; counter < gradeFrequency.length; counter++)
{
int a = counter * 10;
int b = counter * 10 +9;
int y;
if (counter == 0)
y = 50;
else
y = 50 + (counter *25);
// output bar label
if (counter==10)
g.drawString("100:",50,y);
else
g.drawString(a + " - " + b + ": ",25,y);
if (gradeFrequency[counter] != 0)
{
int x = 80;
for(int stars = 0; stars < gradeFrequency[counter];stars++)
{
g.drawString("*", x, y);
x = x+5;
}
}
}
if (gradeCounter != 0)
{
//calculate average of all grades entered
classAverage = total/gradeCounter;
g.drawString("Total: " + total,25,350);
g.drawString("Number of grades: " + gradeCounter, 25, 375);
g.drawString("Average: " + classAverage, 25, 400);
}
}
}