gpt4 book ai didi

java - 为什么在为对象设置值时会收到 NullPointerExceptions?

转载 作者:行者123 更新时间:2023-12-01 17:15:59 25 4
gpt4 key购买 nike

我创建了一个包含 ID、GPA 和 Credits 值的 Student 类,然后在 StudentList 类中创建了一个包含 100 个元素的数组。当尝试写入元素时,我收到 NullPointerException。

学生类(class):

package com.ahellhound.pkg202studentrecordproject;

public class Student {
private String studentID;
private double studentGPA;
private int creditHours;

public void Student() {}

public String getStudentID() {return studentID;}
public void setStudentID(String studentID) {this.studentID = studentID;}

public double getStudentGPA() {return studentGPA;}
public void setStudentGPA(double studentGPA) {this.studentGPA = studentGPA;}

public int getCreditHours() {return creditHours;}
public void setCreditHours(int creditHours) {this.creditHours = creditHours;}

/**
* @return StudentID, StudentGPA, StudentCreditHours separated by spaces
*/
@Override
public String toString() {
return String.format("%s %f.2 $d", studentID, studentGPA, creditHours);
}

}

然后在 StudentList 中,我尝试向其传递三个参数:

    private Student[] studentArray = new Student[100];
private int counter = 0;

public String addStudentRecord(String studentID, double studentGPA, int studentCredits){

studentArray[counter].setStudentID(studentID);
studentArray[counter].setStudentGPA(studentGPA);
studentArray[counter].setCreditHours(studentCredits);
String arrayString = studentArray[counter].toString();

counter++;

return arrayString;

}

最佳答案

这将创建一个数组,最多可容纳 100 个 Student 对象:

private Student[] StudentArray = new Student[100]

但是它不会创建任何学生,因此每个单元格都包含 null。

使用此行 studentArray[counter].setStudentID(studentID); 意味着您尝试在 null 对象上调用 setStudentID(studentID),因为 studentArray[0 ] 为空。

最好的方法是在 Student 类中创建构造函数

public Student(String studentID, double studentGPA, int creditHours) {
this.studentID = studentID;
this.studentGPA = studentGPA;
this.creditHours = creditHours;
}

然后您可以使用以下命令添加学生:

studentArray[counter] = new Student(studentID, studentGPA, creditHours);

关于java - 为什么在为对象设置值时会收到 NullPointerExceptions?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22135562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com