填充对象数组中的对象,空指针异常

时间:2018-01-17 19:56:32

标签: java

在我的addStudent方法中,我试图在对象数组中添加学生(对象),但是当我在那里添加一个对象时,我收到nullPointerException。

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

我也不确定我是否可以只调用5次方法并填充数组中的每个学生,或者我必须循环遍历数组才能这样做。 Internet上的大部分信息都是使用ArrayList,但我无法使用它。

1 个答案:

答案 0 :(得分:1)

您正在构造函数中重新声明名为students的变量,而不是使用StudentGoup的名为students的成员变量

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

您无需再次向学生添加该类型,只需执行

即可
students = new Student[5];

或者

this.students = new Student[5];

在你的构造函数