71.2k views
4 votes
A teacher wants to create a list of students in her class. Using the existing Student class in this exercise. Create a static ArrayList called classList that adds a student to the classList whenever a new Student is created. In the constructor, you will have to add that Student to the ArrayList.

User Gorf
by
3.0k points

1 Answer

1 vote

Answer:

Check the explanation

Step-by-step explanation:

CODE:-

import java.util.ArrayList;

class Student

{

private String name;

private int grade;

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;

}

/*Don't change the code in this method!

This method will print out all the Student names in the classList Array

*/

public static String printClassList()

{

String names = "";

for(Student name: classList)

{

names+= name.getName() + "\\";

}

return "Student Class List:\\" + names;

}

}

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);

Student smith = new Student("Smith", 11);

Student kane = new Student("Kane", 10);

Student virat = new Student("Virat", 12);

Student abd = new Student("ABD", 12);

Student root = new Student("Root", 12);

System.out.println(Student.printClassList());

}

}

Kindly check the attached image below.

A teacher wants to create a list of students in her class. Using the existing Student-example-1
User Psms
by
3.9k points