java - NullPointerException java 错误

标签 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 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/

相关文章:

android - API 15 上的 SupportAppCompat-v7 库中的 NullPointerException

java - 降低 Java 程序的复杂性

java - Play Framework - 删除对象后无法在 session 中找到用户 ID

遍历非空记录集时出现 Java NullPointerException

android - "Attempt to Invoke Virtual Method"到底是什么意思?

java - maven-remote-resources-plugin 不复制文件,仅复制文件夹结构

java - 如何在 Android 中发送带有 fragment 的 graphql 查询

java - 如何在 Play Framework 2.2 中自定义 unmanagedResourceDirectories 和 exceptFilter?

java - 哪个线程获取哪个对象的锁?

java - Kotlin Cast EditText、TextView 来查看