NullPointerException在main()内发生。

huangapple go评论99阅读模式
英文:

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 = &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

你忘记实例化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);
        }

    }

huangapple
  • 本文由 发表于 2023年8月10日 18:26:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76874858.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定