我仍在开始学习 OOP,并且我的代码中不断出现此错误;说线程“main”java.lang.NullPointerException中的异常
public class SlumbookDriver{
public static void main(String args[]){
Slumbook[] contacts = new Slumbook[19];
... // index is an int and is the value of the index of the array
... // i feed it to a function "void viewEntry" that just shows
// the other attributes of the class Slumbook
viewEntry(index, contacts);
}
}
然后我有函数viewEntry
public static void viewEntry(int index, Slumbook[] contacts){
Scanner sc = new Scanner(System.in);
if(index == 0){
System.out.println("Array is empty");
}
else{
String id = contacts[index].getIdNo();
System.out.println("Please enter ID number");
String idNo = sc.next();
if(id != idNo){
while(id != idNo && index != -1){
index--;
id = contacts[index].getIdNo();
}
if(index == -1){
System.out.println("ID does not exist");
return; //terminate action since the ID number does not exist
}
}
System.out.println(contacts[index].viewDetails());
}
}
最佳答案
您只是初始化数组
Slumbook[] contacts = new Slumbook[19];
但不是它的元素,因此当您在如下语句中访问数组元素时,您将得到一个 NullPointerException
:
String id = contacts[index].getIdNo();
当你创建一个对象数组时,数组中的对象并没有被初始化,你需要在使用它们之前使用new
运算符来初始化它们。像这样的事情:
contacts[index] = new Slumbook();
关于java - NullPointerException java 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27750788/