-1

In my addStudent method I am trying to add students(objects) in an object array, but I receive nullPointerException when I add even one object there.

package task2;

public class StudentGroup {
    String groupSubject;
    Student[] students;
    int freePlaces;

    StudentGroup(){
        Student[] students = new Student[5];
        freePlaces = 5;
    }
    StudentGroup(String subject){
        this();
        this.groupSubject = subject;
    }

    void addStudent(Student s){
        if(freePlaces > 0 && s.subject.equals(this.groupSubject)) {        
            this.students[this.freePlaces-1] = s;                                      //check mistake?
            freePlaces--;
        }
        else{
            System.out.println("Student isn't from same subject or there aren't any free spaces!");
        }
    }

    void emptyGroup(){
        Student[] students = new Student[5];
        freePlaces = 5;
    }

    String bestStudent(){
        double highestGrade = students[0].grade;
        String name = students[0].name;
        for (int i = 1; i < students.length; i++) {
            if(students[i].grade > highestGrade){
                highestGrade = students[i].grade;
                name = students[i].name;
            }
        }
        return name;
    }

    void printStudentsInGroup(){
        for (int i = 0; i < students.length; i++) {
            System.out.println(students[i].name + "-" + students[i].grade);
        }
    }
}

I am also not sure if I can just call 5 times the method and fill every student in the array or I have to loop over the array to do so. Most of the info on Internet is with ArrayList, but I can't use it.

Georgi Michev
  • 764
  • 5
  • 18
  • 37

1 Answers1

1

You are re-declaring the variable called students in the constructor instead of using your StudentGoup's member variable called students

Student[] students = new Student[5]; //creating a NEW variable call students...

You don't need to add the type again to students, Just do

students = new Student[5];

Or

this.students = new Student[5];

in your constructor

RAZ_Muh_Taz
  • 4,059
  • 1
  • 13
  • 26