NullPointerException在main()内发生。

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

NullPointerException inside main()

问题

  1. class Book {
  2. String name;
  3. String author;
  4. }
  1. class BookTest {
  2. public static void main(String[] args) {
  3. Book[] books = new Book[2];
  4. books[0].name = "The graps";
  5. books[0].author = "Siffyu";
  6. books[1].name = "Nova supreme";
  7. books[1].author = "Jagga";
  8. for (int i = 0; i < books.length; i++) {
  9. System.out.println(books[i].name + ": " + books[i].author);
  10. }
  11. }
  12. }

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. class Book {
  2. String name;
  3. String author;
  4. }
  1. class BookTest {
  2. public static void main(String[] args) {
  3. Book[] books = new Book[2];
  4. books[0].name = &quot;The graps&quot;;
  5. books[0].author = &quot;Siffyu&quot;;
  6. books[1].name = &quot;Nova supreme&quot;;
  7. books[1].author = &quot;Jagga&quot;;
  8. for (int i = 0; i &lt; books.length; i++) {
  9. System.out.println(books[i].name + &quot;: &quot; + books[i].author);
  10. }
  11. }
  12. }

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();

  1. public static void main(String[] args) {
  2. Book[] books = new Book[2];
  3. books[0] = new Book();
  4. books[0].name = "The graps";
  5. books[0].author= "Siffyu";
  6. books[1] = new Book();
  7. books[1].name = "Nova supreme";
  8. books[1].author = "Jagga";
  9. for (int i = 0; i < books.length; i++) {
  10. System.out.println(books[i].name + ": " + books[i].author);
  11. }
  12. }
英文:

You forgot to instantiate the Book object :
books[1] = new Book();

  1. public static void main(String[] args) {
  2. Book[] books = new Book[2];
  3. books[0] = new Book();
  4. books[0].name = &quot;The graps&quot;;
  5. books[0].author= &quot;Siffyu&quot;;
  6. books[1] = new Book();
  7. books[1].name = &quot;Nova supreme&quot;;
  8. books[1].author = &quot;Jagga&quot;;
  9. for (int i = 0; i &lt; books.length; i++) {
  10. System.out.println(books[i].name + &quot;: &quot; + books[i].author);
  11. }
  12. }

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:

确定