英文:
NullPointerException inside main()
问题 {#heading}
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}
得分: 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 = &quot;The graps&quot;;
books[0].author= &quot;Siffyu&quot;;
books[1] = new Book();
books[1].name = &quot;Nova supreme&quot;;
books[1].author = &quot;Jagga&quot;;
for (int i = 0; i &lt; books.length; i++) {
System.out.println(books[i].name + &quot;: &quot; + books[i].author);
}
}