NullPointerException java错误

NullPointerException java错误,java,nullpointerexception,Java,Nullpointerexception,我仍在学习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 t

我仍在学习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();
   contacts[index] = new Slumbook();
创建对象数组时,数组中的对象未初始化,在使用它们之前,需要使用
new
操作符初始化它们。大概是这样的:

    String id = contacts[index].getIdNo();
   contacts[index] = new Slumbook();

这里的问题是您已经初始化了SlumBook的数组,但是需要初始化数组的内容。 对于初学者,只需初始化内容:

for (int i = 0; i < contacts.length; i++)
{
    contacts[i] = new SlumBook();
}
for(int i=0;i

在方法
viewEntry(int,SlumBook[])

中使用联系人之前请执行此操作,当您尝试访问引用中的字段或方法但该引用为空时,会发生
NullPointerException

比如说

Slumbook a = null;
a.getIdNo(); // NullPointerException
如果您有一个数组,也会发生同样的情况

Slumbook [] data = new Slumbook[N];
data[i].getIdNo(); /// NPE
第二个示例将在位置
i
包含的引用恰好为空时抛出NPE


当您收到异常时,将显示堆栈跟踪,其中包含发生异常的文件名和确切行号(大多数情况下)

是的,我已经这样做了,用另一个函数中的对象填充我的数组,但错误仍在弹出out@user253938你可能拿不到正确的参考资料。发布您的完整代码。谢谢,但似乎只有当索引变为0时才会弹出错误(我真的不知道为什么会发生这种情况,联系人[0]已赋值,所以不能为空),所以为了解决这个问题,我只将联系人[0]保留为空,将其从程序中删除,并从联系人[1]上的数组开始,现在它运行得很好。您是否可以发布更多的代码,以及使用异常打印的堆栈跟踪?这将有助于查明问题所在。