The following code will be applied to Create the following static methods for the Student class
<u>Explanation:</u>
/* Note: Array index starts from 0 in java so ,, user ask for 1 index then the position will be i-1 , below program is based on this concept if you dont want this way just remove -1 from classList.get(i-1).getName(); ,and classList.add(i-1,student); */
/* ClassListTester.java */
public class ClassListTester
{
public static void main(String[] args)
{
//You don't need to change anything here, but feel free to add more Students!
Student alan = new Student("Alan", 11);
Student kevin = new Student("Kevin", 10);
Student annie = new Student("Annie", 12);
System.out.println(Student.printClassList());
System.out.println(Student.getLastStudent());
System.out.println(Student.getStudent(1));
Student.addStudent(2, new Student("Trevor", 12));
System.out.println(Student.printClassList());
System.out.println(Student.getClassSize());
}
}
/* Student.java */
import java.util.ArrayList;
public class Student
{
private String name;
private int grade;
//Implement classList here:
private static ArrayList<Student> classList = new ArrayList<Student>();
public Student(String name, int grade)
{
this.name = name;
this.grade = grade;
classList.add(this);
}
public String getName()
{
return this.name;
}
//Add the static methods here:
public static String printClassList()
{
String names = "";
for(Student name: classList)
{
names+= name.getName() + "\n";
}
return "Student Class List:\n" + names;
}
public static String getLastStudent() {
// index run from 0 so last student will be size -1
return classList.get(classList.size()-1).getName();
}
public static String getStudent(int i) {
// array starts from 0 so i-1 will be the student
return classList.get(i-1).getName();
}
public static void addStudent(int i, Student student) {
// array starts from 0 so, we add at i-1 position
classList.add(i-1,student);
// remove extra student
classList.remove(classList.size()-1);
}
public static int getClassSize() {
return classList.size();
}
}