开发者

Java program runtime error

public class BooksTestDrive {
 public static void main(String[] args) {

  Books [] myBooks = new Books[3];
  int x=0;
  myBooks[0].title = "The Grapes of Jave";
  myBooks[1].title = "The Java Gatsby";
  myBooks[2].title = "The Java Cookbook";
  m开发者_JS百科yBooks[0].author = "bob";
  myBooks[1].author = "sue";
  myBooks[2].author = "ian";

 while (x < 3) {
  System.out.print(myBooks[x].title);
  System.out.print("by");
  System.out.println(myBooks[x].author);
  x = x+1;
  }
 }
}

This code compiles but while runtime, its giving nullpointer exception.


Your allocation of MyBooks[3] only assigns the array You still need to assign a "new MyBook()" to each entry in your array.


look at your line:

Books [] myBooks = new Books[3];

you create an array, although every element in the array is a null pointer.


Saw it, you need to initializate each one of the elments of your array, try it with in an for or a while


This should work :

public class BooksTestDrive {
public static void main(String[] args) { 
      Books [] myBooks = new Books[3];
      // init loop
      for (int i=0;i<myBooks.length;i++) {
         myBooks[i] = new Books();
      }

      myBooks[0].title = "The Grapes of Jave";
      myBooks[1].title = "The Java Gatsby";
      myBooks[2].title = "The Java Cookbook";
      myBooks[0].author = "bob";
      myBooks[1].author = "sue";
      myBooks[2].author = "ian";

      for (Books book : myBooks) {
          System.out.printf("%s by %s\n",book.title,book.author);
      }
     }
}
}


You need to add the books to the arrays. This should work:

class BooksTestDrive {
    public static void main(String [] args) {
        Books [] myBooks = new Books[3];
        int x = 0;
        // THIS IS WHAT WAS MISSING.
        myBooks[0] = new Books();
        myBooks[1] = new Books();
        myBooks[2] = new Books();

        myBooks[0].title = "The Grapes of Java";
        myBooks[1].title = "The Java Gatsby";
        myBooks[2].title = "The Java Cookbook";
        myBooks[0].author = "bob";
        myBooks[1].author = "sue";
        myBooks[2].author = "ian";

        while (x < 3) {
            System.out.print(myBooks[x].title);
            System.out.print(" by ");
            System.out.println(myBooks[x].author) ;
            x = x + 1;
        }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜