我有以下程序:
class Books
{
String title;
String author;
}
class BookTestDrive
{
public static void main(String [] args)
{
Books [] myBooks = new Books[3];
int x = 0;
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;
}
}
}
但是,执行该命令时会出现以下错误:
Exception in thread "main" java.lang.NullPointerException
at BookTestDrive.main(Books.java:14)
我是Java新手。从我的C / C ++经验来看,代码看起来是合法的...如何解决此问题?
最佳答案
问题是您仅在以下几行中创建了一系列图书:
Books [] myBooks = new Books[3];
在访问它们之前,您仍然需要将数组中的每个元素初始化为book对象。
示例代码如下所示:
Books [] myBooks = new Books[3];
int x = 0;
myBooks[0] = new Books();
myBooks[0].title = "The Grapes of Java";
您需要对数组中的所有元素执行此操作。