在调用getter方法时获取NullPointerException

时间:2019-03-10 13:38:35

标签: java

我有三个班级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);
}

}

学生服务代码:

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

}

我在StudentService类的if(data[i].getMarks()==null)if(data[i].getMarks()=null)遇到异常。

1 个答案:

答案 0 :(得分:0)

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

因此,您需要确保您具有对象和数组。