Java 填充对象数组中的对象,空指针异常
在我的addStudent方法中,我试图在对象数组中添加学生(对象),但当我在其中添加一个对象时,我会收到nullPointerExceptionJava 填充对象数组中的对象,空指针异常,java,Java,在我的addStudent方法中,我试图在对象数组中添加学生(对象),但当我在其中添加一个对象时,我会收到nullPointerException package task2; public class StudentGroup { String groupSubject; Student[] students; int freePlaces; StudentGroup(){ Student[] students = new Student[5
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);
}
}
}
包任务2;
公共班级学生小组{
字符串组主题;
学生[]学生;
国际自由地;
学生组(){
学生[]学生=新生[5];
自由空间=5;
}
学生组(弦乐科目){
这个();
this.groupSubject=subject;
}
无效添加学生(学生s){
如果(自由空间>0&&s.subject.equals(this.groupSubject)){
this.students[this.freePlaces-1]=s;//检查错误?
自由地--;
}
否则{
System.out.println(“学生不是来自同一科目,或者没有任何可用空间!”);
}
}
void emptyGroup(){
学生[]学生=新生[5];
自由空间=5;
}
字符串bestStudent(){
双高年级=学生[0]。年级;
字符串名称=学生[0]。名称;
for(int i=1;i最高成绩){
最高年级=学生[i]。年级;
姓名=学生[i]。姓名;
}
}
返回名称;
}
void printStudentsInGroup(){
for(int i=0;i
我也不确定我是否可以只调用5次该方法并填充数组中的每个学生,或者我必须循环数组才能这样做。Internet上的大多数信息都是ArrayList,但我无法使用它。您在构造函数中声明名为students的变量,而不是使用StudentGoup的名为students的成员变量
Student[] students = new Student[5]; //creating a NEW variable call students...
您不需要再次向学生添加类型,只需这样做即可
students = new Student[5];
或
在构造器中键入:
students=newstudent[5]代码>。。。
this.students = new Student[5];