import java.util.ArrayList;
/**
*
* CMP 326 Project 5
*
*
- A
Student object should keep track of a first name and a last name. These should be set by the constructor. There should be getFirst and getLast accessor methods, but no methods to change names.
- A
Student object should keep track of a list of grades. Grades are double. The list should be maintained using an ArrayList object. Make use of generics so that the ArrayList stores objects of type Double.
- There should be a method called
addGrade, with a parameter of type double. The method should add that parameter to the list of grades.
- There should be a method called
getAverage, with no parameters. It should return the average of grades entered so far. Averages are not defined if no grades have been entered; in this case, return -1.
- Every object inherits a
toString method but the inherited one can be overridden. Do that for Student. For example, if the student is George Washington and the average is 87.5, toString should return the string "George Washington: average = 87.5". But also, if the student is George Washington and no grades have been entered then toString should return the string "George Washington: no grades entered". Student should be made to implement the Comparable interface. Student objects should be sorted by average.
*
* @author Melvin Fitting
* @version Feb 22, 2008
*
*/
public class Student implements Comparable {
private String first, last;
private ArrayList gradeList = new ArrayList();
/**
*
* @param first Student first name
* @param last Student last name
*/
public Student(String first, String last){
this.first = first;
this.last = last;
}
/**
*
* @return Student first name
*/
public String getFirst(){
return first;
}
/**
*
* @return Student last name
*/
public String getLast(){
return last;
}
/**
* Adds a grade to the student's list of grades
*
* @param grade the grade to be added
*/
public void addGrade(double grade){
gradeList.add(grade);
}
/**
*
* @return student's average, or -1 if no grades entered
*/
public double getAverage(){
if (gradeList.isEmpty()) return -1;
double sum = 0;
for (int n = 0; n < gradeList.size(); n++)
sum += gradeList.get(n);
return sum/gradeList.size();
}
public String toString(){
double average = getAverage();
if (average < 0) return first + " " + last + " : no grades entered";
else return first + " " + last + " : average = " + average;
}
public int compareTo(Object otherObject){
Student other = (Student)otherObject;
double myAverage = getAverage();
double otherAverage = other.getAverage();
if (myAverage < otherAverage) return -1;
else if (myAverage > otherAverage) return +1;
else return 0;
}
}