how about the following:
// assume students.length > 0
static void printMinMax(Student[] students) {
Student min = students[0];
Student max = students[0];
for (Student student: students) {
if (student.getGrade() > max.getGrade())
max = student;
if (student.getGrade() < min.getGrade())
min = student;
}
System.out.println("Best student: " + max);
System.out.println("Worst student: "+ min);
}
On another note, you should really consider using Collections instead of plain arrays. Especially since you do not really know the number of students beforehand.
Above code could be rewritten like this:
static void printMinMax(List<Student> students) {
Comparator<Student> comparator = new Comparator<>() {
@Override public int compare(Student s1, Student s2) {
return s1.getGrade() - s2.getGrade();
}
};
Student max = Collections.max(students, comparator);
Student min = Collections.min(students, comparator);
// print stuff
}
or shorter using java 8 lambdas:
static void printMinMax(List<Student> students) {
Comparator<Student> comparator = (s1, s2) -> s1.getGrade() - s2.getGrade();
Student max = Collections.max(students, comparator);
Student min = Collections.min(students, comparator);
// print stuff
}