提问人:Vijay 提问时间:8/10/2023 最后编辑:user2340612Vijay 更新时间:8/10/2023 访问量:48
main() 中的 NullPointerException [重复]
NullPointerException inside main() [duplicate]
问:
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。
答:
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);
}
}
评论
book[0] = new Book()
book[1] = new Book()
null