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 = &quot;The graps&quot;;
        books[0].author = &quot;Siffyu&quot;;
        
        
        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);
        }

    }
}

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 = &amp;quot;The graps&amp;quot;;
        books[0].author= &amp;quot;Siffyu&amp;quot;;
        
        books[1] = new Book();
        books[1].name = &amp;quot;Nova supreme&amp;quot;;
        books[1].author = &amp;quot;Jagga&amp;quot;;

        for (int i = 0; i &amp;lt; books.length; i++) {
            System.out.println(books[i].name + &amp;quot;: &amp;quot; + books[i].author);
        }

    }


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