Reputation: 21
I'm tutoring a high school student and she has a CS assignment that I don't know how to help her with.
She is supposed to "write a method that will take an array of students and return the student with the highest GPA."
The code given states
public class Student {
private String myName;
private double my GPA;
public Student (String n, double gpa) {
myName = n;
myGPA = gpa;
}
public String getName() {
return myName;
}
public double getGPA() {
return myGPA;
}
/* other methods not shown */
}
We know what they are asking, but we don't know exactly how to do it. We say they are asking us to sort people and their GPA, and then return JUST the student who has the highest GPA. Should we sort first, and then extract? Is there anything else going on?
Upvotes: 1
Views: 1449
Reputation: 1823
One way of doing it is by making Student implement Comparable:
public class Student implements Comparable<Student>{
...
int compareTo(Student s){
return Double.valueOf(myGPA).compareTo(s.getGPA())
}
...
}
And then use:
Collections.sort(studentlist);
studentlist.get(0);
EDIT: Adjusted the code to work with primitive doubles, thanks to @ThanksForAllTheFish comment
Upvotes: 2