229k views
3 votes
Now that the classList Array has been implemented, we need to create methods to access the list items.

Create the following static methods for the Student class:

1. getLastStudent() - returns the name of the last student in
the classList array

2. getClass Size() - returns the size of the classList

3. addStudent(int index, Student student) - adds a new student to
the classList at index index. This method is a little tricky - when the
new Student is added to the class, it will create a duplicate value at the
end of the classList because of our student constructor. This method
should also include a command to remove the extra student in
the classList added to the end.

4. getStudent(int index) - returns the name of a student at the index
specified

User Jcklie
by
3.0k points

1 Answer

2 votes

The following code will be applied to Create the following static methods for the Student class

Step-by-step explanation:

/* 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() + "\\";

}

return "Student Class List:\\" + 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();

}

}

User Gspr
by
3.9k points