main() 中的 NullPointerException [重复]

NullPointerException inside main() [duplicate]

提问人:Vijay 提问时间:8/10/2023 最后编辑:user2340612Vijay 更新时间:8/10/2023 访问量:48

问:

class Book {
    String name;
    String author; 
}
class BookTest {

    public static void main(String[] args) {
         
        Book[] books = new Book[2];

        books[0].name = "The graps";
        books[0].author = "Siffyu";
        
        
        books[1].name = "Nova supreme";
        books[1].author = "Jagga";

        for (int i = 0; i < books.length; i++) {
            System.out.println(books[i].name + ": " + books[i].author);
        }

    }
}

我尝试创建一个可以保存 Book 类型对象的数组。创建数组后,我初始化数组中的书籍对象并尝试打印它们。我得到了NullPointerException。

Java NullPointerException

评论

0赞 crizzis 8/10/2023
你是否习惯于使用具有价值(堆栈分配)对象的语言进行编程?在 java 中,除了简单类型之外,其他所有内容都有引用语义。也就是说,您需要首先分配 和 ,否则它们只是引用。book[0] = new Book()book[1] = new Book()null

答:

1赞 DEV 8/10/2023 #1

你忘了实例化 Book 对象: books[1] = new Book();

public static void main(String[] args) {
        
        Book[] books = new Book[2];
        
        books[0] = new Book();
        books[0].name = "The graps";
        books[0].author= "Siffyu";
        
        books[1] = new Book();
        books[1].name = "Nova supreme";
        books[1].author = "Jagga";

        for (int i = 0; i < books.length; i++) {
            System.out.println(books[i].name + ": " + books[i].author);
        }

    }