In: Computer Science
JAVA: How do I fix the last "if" statement in my code so that
outputs the SECOND HIGHEST/MAXIMUM GPA out of the given
classes?
public class app {
private static Object minStudent;
private static Object maxStudent;
public static void main(String args[ ])
{
student st1 = new student("Rebecca", "Collins", 22, 3.3);
student st2 = new student("Alex", "White", 19, 2.8);
student st3 = new student("Jordan", "Anderson", 22, 3.1);
student[] studentArray;
studentArray = new student[3];
studentArray[0] = st1;
studentArray[1] = st2;
studentArray[2] = st3;
for (student studentArray1 : studentArray) {
int min; min = (int) studentArray[0].gpa;
int max; max = (int) studentArray[0].gpa;
System.out.println("Name: " + studentArray1.firstName + " " +
studentArray1.lastName);
System.out.println("Age: " + studentArray1.age);
System.out.println("GPA: " + studentArray1.gpa);
{
if (studentArray1.gpa < max) {
System.out.println(studentArray1.firstName + " has the minimun GPA
of " + studentArray1.gpa);
}
if (studentArray1.gpa >= max) {
System.out.println(studentArray1.firstName + " has the maximun GPA
of " + studentArray1.gpa);
}
if(studentArray1.gpa > min){
System.out.println(studentArray1.firstName + " has the second
maximum GPA of " + studentArray1.gpa);
}
}
}
}
}
class student { public String firstName; public String lastName; public int age; public double gpa; public student(String firstName, String lastName, int age, double gpa) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.gpa = gpa; } } class app { private static Object minStudent; private static Object maxStudent; public static void main(String args[]) { student st1 = new student("Rebecca", "Collins", 22, 3.3); student st2 = new student("Alex", "White", 19, 2.8); student st3 = new student("Jordan", "Anderson", 22, 3.1); student[] studentArray; studentArray = new student[3]; studentArray[0] = st1; studentArray[1] = st2; studentArray[2] = st3; student min = studentArray[0], max = studentArray[0], secondMax = studentArray[0]; if (studentArray[0].gpa > studentArray[1].gpa) { secondMax = studentArray[1]; } for (student s : studentArray) { System.out.println("Name: " + s.firstName + " " + s.lastName); System.out.println("Age: " + s.age); System.out.println("GPA: " + s.gpa + "\n"); if (s.gpa > max.gpa) { secondMax = max; max = s; } else if (s.gpa > secondMax.gpa && s.gpa != max.gpa) { secondMax = s; } if (s.gpa < min.gpa) min = s; } System.out.println(min.firstName + " has the minimum GPA of " + min.gpa); System.out.println(max.firstName + " has the maximum GPA of " + max.gpa); System.out.println(secondMax.firstName + " has the second maximum GPA of " + secondMax.gpa); } }