Java 为什么我会得到这个循环的NullPointerException?
我正在编写一个for循环来遍历数组,并找到社保号为123456789的员工的索引。为什么我总是得到一个NullPointerException .getSocSecNum()返回一个字符串Java 为什么我会得到这个循环的NullPointerException?,java,loops,nullpointerexception,compareto,Java,Loops,Nullpointerexception,Compareto,我正在编写一个for循环来遍历数组,并找到社保号为123456789的员工的索引。为什么我总是得到一个NullPointerException .getSocSecNum()返回一个字符串 empnew[21] = Empthe1; String temp = "123456789" for(int i = 0; i < empnew.length - 1; i++){ if(empnew[i].getSocSecNum().compareTo(temp) == 0){ System.ou
empnew[21] = Empthe1;
String temp = "123456789"
for(int i = 0; i < empnew.length - 1; i++){
if(empnew[i].getSocSecNum().compareTo(temp) == 0){
System.out.println("the location of the employee is " + i);
}
}
empnew[21]=Empthe1;
字符串温度=“123456789”
for(int i=0;i
我希望它输出“员工的位置是21”,但我得到的只是一个NullPointerException问题很可能是
empnew
中至少有一个null
因此,在循环中,您尝试获取empnew[i].getSocSecNum()
,它将扩展为null.getSocSecNum()
,这会给您一个空指针异常,因为您无法访问null
上的类成员,因为它不是真正的对象
最简单的解决方案可能是检查empnew[i]!=在访问该值之前,null
:
if (empnew[i] != null && empnew[i].getSocSecNum...) {
...
}
到目前为止你试过什么?特别是,您是否尝试打印出数组或各种中间值,以查看某处是否存在
null
?(或者,如果您不明白什么是NullPointerException
,请看一下的答案。)每当我尝试这样打印数组时,它只会给我一个Nullpointer,是不是因为我的数组没有完全填充???似乎是这样的,是的。尝试在循环之前使用或打印阵列。