英文:
NullPointerException inside main()
问题
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);
}
}
}
I tried creating an array that can hold Book type object. Once I created the array, I then initialized the book objects inside the array and tried to print them. I got NullPointerException instead.
英文:
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);
}
}
}
I tried creating an array that can hold Book type object. Once I created the array, I then initialized the book objects inside the array and tried to print them. I got NullPointerException instead.
答案1
得分: 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);
}
}
英文:
You forgot to instantiate the Book object :
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);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论