Pie Chart Applet (Version#2)
File: PieChart.java
Purpose: Given the number of students in class that will major in
each discipline, depict the data as a pie chart.
Notes: Version 2
The applet is a second version of a Java program that performs some simple
computations uses the paint method to display the data visually.
In this version, we have created methods to separate out various tasks.
We took the Version 1 and modified it into this version.
NOTE: In the process of modifying from version 1, we have inadvertently
introduced an error in the program! Can you tell what it is?
HINT: Scroll down this page until the applet above is no longer visible.
Then scroll back up again. Do you see the problem? Do you know how
to correct the situation? Send me an e-mail with your correction.
If your solution is correct, you will get 1 Home Work equivalent
of EXTRA CREDIT! [All answers should be due by Tue 2/12 2:00 pm]
*/
import java.awt.*;
import java.applet.Applet;
public class PieChart extends Applet {
// variables to store the number of students in each discipline
int Sci, Soc, Hum;
// variables to store percentages should be float
float PercSci, PercSoc, PercHum;
// the coordinates and size of the pie is fixed below
int x = 50, y = 50, w = 100, h = 100;
// these quantities will need to be computed for each slice
int startAngle = 0, degrees;
public void init() {
// Set # of students in each discipline
Sci = 5;
Soc = 6;
Hum = 7;
compute();
} // end of init
private float perc(int x, int t) { // computes the percentage of x over t
return x * 100.0f/t;
} // end of perc
public void compute() { // does the required computations
// the total number of students
int Total;
// Computer percentages
Total = Sci + Soc + Hum;
PercSci = perc(Sci, Total);
PercSoc = perc(Soc, Total);
PercHum = perc(Hum, Total);
//PercSci = Sci * 100.0f / Total;
//PercSoc = Soc * 100.0f / Total;
//PercHum = Hum * 100.0f / Total;
// Print out results for checking
System.out.println("Total = " + Total);
System.out.println("%Sci = " + PercSci);
System.out.println("%Soc = " + PercSoc);
System.out.println("%Hum = " + PercHum);
} // end of compute
public void paint(Graphics g) {
// Display the Pie Chart
// Display the Pie for Sciences
degrees = (int) (PercSci*360/100);
g.setColor(Color.red);
g.fillArc(x, y, w, h, startAngle, degrees);
// Pie for Soc
startAngle = degrees;
degrees = (int) (PercSoc*360/100);
g.setColor(Color.yellow);
g.fillArc(x, y, w, h, startAngle, degrees);
// Pie for Hum
startAngle = startAngle + degrees;
degrees = (int) (PercHum*360/100);
g.setColor(Color.green);
g.fillArc(x, y, w, h, startAngle, degrees);
} // end of paint
} // end of applet