-1

so basically i want to put the class "GradeBook", which contains 2 arraylists, inside another class "course". I create a setCourse method to link both class together but when I tried to put in the GradeBook inside a list "gradebooks" inside "course" class, there's a NullPointerException. Why can't I put this class i the list.

public class GradeBook {

 private List<Double> assignmentScores;
 private List<Double> quizScores;
 private Course course;

 public GradeBook() {
    assignmentScores = new ArrayList<>();
    quizScores = new ArrayList<>();
 }
 public void setCourse(Course course) {
    this.course = course;
 }

public class Course {

private List<GradeBook> gradeBooks;

public void addGradebook(GradeBook gradebook) {
    gradebook.setCourse(this);
    gradeBooks.add(gradebook);
}
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76

1 Answers1

2

You need to initialize gradeBooks. You are getting the null pointer because gradeBooks is null when you try to add a grade book. As an example, you could initialize it in a constructor of the Course class.

public Course() {
    gradeBooks = new ArrayList<>();
}

public void addGradebook(GradeBook gradebook) {
    gradebook.setCourse(this);
    gradeBooks.add(gradebook);
}
secondbreakfast
  • 4,194
  • 5
  • 47
  • 101