51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

NullPointerException在main()内发生。

英文:

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 = "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);
}

}



赞(4)
未经允许不得转载:工具盒子 » NullPointerException在main()内发生。