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;
}
return collection of ArrayList from a constructor
-
20-06-2023 - |
سؤال
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.
المحلول 2
نصائح أخرى
In getStudentsByMajor
:
- creates a fresh list of student (empty)
- iterates over existing students (
studentList
) - for each student check major
- if major ok add to the new list
- return the new list
لا تنتمي إلى StackOverflow