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


该代码可以编译,但在运行时会给出nullpointer异常。

最佳答案

您对MyBooks [3]的分配仅分配了数组。您仍然需要为数组中的每个条目分配一个“ new MyBook()”。

10-07 15:26