第14行出现空指针异常

时间:2019-02-28 19:50:00

标签: java object

我在代码的第9行遇到空指针异常,我对java很陌生,可以告诉我我正在做的概念和错误。

public static void main(String[] args) {
    Certificate certificate1= new Certificate(60,"cnexirk","cbnifms",77);
    Certificate certificate2= new Certificate(45,"gphspvq","pqjbhmz",62);
    Certificate certificate3= new Certificate(41,"nfpxsmp","vimiopu",89);
    Certificate certificate4= new Certificate(95,"ionouca","bsbknpx",38);
    Certificate certificate5= new Certificate(39,"yhzrafu","itnbskb",44);
    Certificate[] objArray={certificate1,certificate2,certificate3,certificate4,certificate5};
    Certificate[] objResultArray1=getEven(objArray);
    for(Certificate certificate:objResultArray1){
        System.out.println(certificate.getId()+" " + certificate.getTitle()+" " + certificate.getDate()+" " + certificate.getRank()+" ");
    }


public static Certificate[] getEven(Certificate[] cer)
{
    Certificate[] objresult=new Certificate[cer.length];
    for(int i=0;i<cer.length;i++)
    {
        if(cer[i].getRank()==77)
        {
            objresult[i]=cer[i];
        }
    }
return  objresult;
}

} `

1 个答案:

答案 0 :(得分:0)

问题在这里

if (cer[i].getRank() == 77) {
   objresult[i]=cer[i];
}

如果rank不完全是77怎么办?数组元素保留为null
然后,在循环返回的数组objResultArray1

certificate.getId()

抛出NullPointerException

您的objResultArray1数组看起来像

[Certificate@132u323, null, null, null, null]