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.