我有以下程序:
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 ++经验,代码看起来合法......如何解决这个问题?
答案 0 :(得分:11)
问题在于您只在以下行中创建了书籍数组 -
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";
您需要对阵列中的所有元素执行此操作。
答案 1 :(得分:2)
我是@AnandSKumar的答案(毕竟这是问题的直接答案),但因为这是一个美丽的问题,我不能不做几个改变就离开了:
public class Play {
static public class Book {
final public String title;
final public String author;
public Book(String title,String author) {
this.title = title;
this.author = author;
}
@Override
public String toString() {
return "\""+title+"\" by "+author;
}
}
public static void main(String [] args)
{
Book [] books = new Book[] {
new Book("The Grapes of Java","bob"),
new Book("The Java Gatsby","sue"),
new Book("The Java Cookbook","ian"),
};
for (Book book:books) {
System.out.println(book);
}
}
}
Book
而不是Books
以避免混淆。Book
增强toString()
课程,并使用它。for
迭代器可以遍历你的数组。Book
类设计为“不可变”可能是件好事。因此,添加了构造函数,并将title
和author
字段设置为final。您也可以考虑将它们设为私有,并提供吸气剂。