Consider the \"Student\" class containing proper constructors(as used in the fol
ID: 3827425 • Letter: C
Question
Consider the "Student" class containing proper constructors(as used in the following code), and getName() and getGrade() public methods with the obvious meaning. Assume the following code as part of the main method of a TestStudent class: Public static void main(String[] args) {ArrayList list = new Array List(); list.add(new Student("John", 80)); list.add (new Student("Kim", 70)); list.add (new Student("Peter", 92)); list.add (new Student("Sam", 84)); printTopScore(list);} Write the method called printTopScore for the TestStudent class that will print the highest score. Make sure your program will work for any number of students with any score.Explanation / Answer
TestStudent.java
import java.util.ArrayList;
public class TestStudent {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<Student>();
list.add(new Student("John", 80));
list.add(new Student("Kim", 70));
list.add(new Student("Peter", 92));
list.add(new Student("Sam", 84));
printTopScore(list);
}
public static void printTopScore(ArrayList<Student> list){
int maxScore = list.get(0).getGrade();
for(Student s: list){
if(maxScore<s.getGrade()){
maxScore=s.getGrade();
}
}
System.out.println("Highest score: "+maxScore);
}
}
Student.java
public class Student {
private String name;
private int grade;
public Student(String name, int grade){
this.name = name;
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
}
Output:
Highest score: 92