CSE142 Program Example handout #28
A different version of Grade.java
---------------------------------
// Stuart Reges
// 11/29/04
//
// Class Grade stores the information for a single grade (units and grade).
// It also computes the quality points for a given grade.
//
public class Grade {
private int units;
private double grade;
// construct Grade object with given units and grade
public Grade(int units, double grade) {
this.units = units;
this.grade = grade;
}
// returns the units for this grade
public int getUnits() {
return this.units;
}
// returns the quality points for this grade
public double getQualityPoints() {
return this.units * this.grade;
}
// returns a string representation of this grade
public String toString() {
return this.units + "-unit " + this.grade;
}
}
A different version of GradeList.java
--------------------------------------
// Stuart Reges
// 11/29/04
//
// Class GradeList stores a list of grades for a particular person and computes
// a weighted GPA.
//
// This version uses Java's "this" keyword instead of the "my" prefix on
// data fields.
import java.util.*;
public class GradeList {
private String name;
private ArrayList grades;
// constructs an empty grade list for the person with the given name
public GradeList(String name) {
this.name = name;
this.grades = new ArrayList();
}
// adds the given grade to the list of grades
public void add(Grade g) {
this.grades.add(g);
}
// gets the ith grade from the list (0-based indexing)
public Grade get(int i ) {
return (Grade)this.grades.get(i);
}
// returns the number of grades in the list
public int length() {
return this.grades.size();
}
// returns the weighted gpa for this person, 0.0 if no classes taken
public double getGPA() {
int units = 0;
double points = 0.0;
for (int i = 0; i < this.grades.size(); i++) {
Grade g = (Grade)this.grades.get(i);
units += g.getUnits();
points += g.getQualityPoints();
}
if (units == 0)
return 0.0;
else
return points/units;
}
// returns a string representation of this grade list
public String toString() {
return "Grades for " + this.name + " = " + this.grades;
}
}