Question

This beginner homework of mine requires create a method named getStudentsByMajor (String major).

This method returns a collection(ArrayList) of students whose majoring in major.

Here is my progress so far :

    private String courseName;
    private String roomNumber;
    private String Lecturer;
    private ArrayList <Student> studentList;

    public LectureRoom(String roomNumber , String courseName , String Lecturer)
    {

        this.courseName=courseName;
        this.roomNumber=roomNumber;
        this.Lecturer = Lecturer;
        this.studentList = new ArrayList<Student>();
    }

    public void addStudent(String name, String id, String major)
    {
        Student s = new Student(name, id , major);
        studentList.add(s);
    }

    public ArrayList<Student> getStudentsByMajor(String major)
    {

    }

(Part of the question details) Hint:

public ArrayList<Student> getStudentsByMajor(String major)

More hint:

for(ElementType element: collection){
    loop body;
    }

Learning setter and getter, I understand that whenever the word "getter" is there, there is usually no parameter.

What I think would work is something like:

public ArrayList<Student> getStudentsByMajor(String major)
        {
            for( Student a : studentList)
            {
                System.out.println(major)
            }
        }

Obviously it's wrong but I hope I can get some pointers here.

Was it helpful?

Solution 2

public ArrayList<Student> getStudentsByMajor(String major)
{
    ArrayList<Student> students = new ArrayList<>();

    for (Student student : studentList) {
        if (student.getMajor().equals(major))
            students.add(student);
    }

    return students;
}

OTHER TIPS

In getStudentsByMajor:

  1. creates a fresh list of student (empty)
  2. iterates over existing students (studentList)
  3. for each student check major
  4. if major ok add to the new list
  5. return the new list
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top