gpt4 book ai didi

java - 调用 getter 方法时出现 NullPointerException

转载 作者:太空宇宙 更新时间:2023-11-04 09:48:40 24 4
gpt4 key购买 nike

我有三个类(class) StudentMain、StudentService、Student。 Student 类包含 getters 和 setters 方法,并且从 StudentMain 我将 Student 对象传递给 StudentService。下面是代码:

StudentMain 代码:

public class StudentMain {
static Student data [] = new Student[4];
static { for (int i = 0; i < data.length; i++)
data [i] =new Student();
data [0] = new Student ("Sekar", new int [] {35, 35, 35});
data [1] = new Student(null,new int[]{11,22,33});
data [2] = null;
data [3] = new Student ("Manoj", null);

}
public static void main(String[] args) {
// TODO Auto-generated method stub
StudentService studentService = new StudentService ();
System.out.println ("Number of Objects with Marks array as null =" + studentService.findNumberOfNullMarks (data));
System.out.println ("Number of Objects with Name as null="+ studentService.findNumberOfNullNames(data));
System.out.println ("Number of Objects that are entirely null="+ studentService.findNumberOfNullObjects(data));
}

}

学生代码:

public class Student {
private String name;
private int marks[];
public void setName(String name) {
this.name=name;
}
public String getName() {
return name;
}
public void setMarks(int [] marks) {
this.marks=marks;
}
public int[] getMarks() {
return marks;
}
public Student() {

}
public Student(String name,int[] marks) {
setName(name);
setMarks(marks);
}

}

StudentService 代码:

public class StudentService{
Student[] data;
public int findNumberOfNullMarks(Student data[]) {
this.data=data;
int count=0;
int i=0;
while(i!=data.length) {
if(data[i].getMarks()==null)
count++;
i++;
}
return count;
}
public int findNumberOfNullNames(Student data[]) {
int count=0;
int i=0;
while(i!=data.length) {
if(data[i].getName()==null)
count++;
i++;
}
return count;
}
public int findNumberOfNullObjects(Student data[]) {
int count=0;
int i=0;
while(i!=data.length) {
if(data[i]==null)
count++;
i++;
}
return count;
}

}

我在 if(data[i].getMarks()==null) 处遇到异常和if(data[i].getMarks()=null)在学生服务课上。

最佳答案

data [0] = new Student ("Sekar", new int [] {35, 35, 35}); 
data [1] = new Student(null,new int[]{11,22,33});
data [2] = null;
data [3] = new Student ("Manoj", null);

对于 i = 0,data[0] 具有对象并在对象中具有数组标记,因此您不会得到 java.lang.NullPointerException

对于 i = 1,data[1] 具有对象并在对象中具有数组标记,因此您不会得到 java.lang.NullPointerException

对于 i = 2,data[2] 为 null,因此您将得到 java.lang.NullPointerException

对于 i = 3,data[3] 有对象但数组标记为 null,因此您将得到 java.lang.NullPointerException

所以你需要确保你应该有对象和数组。

关于java - 调用 getter 方法时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55088258/

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