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;
}
}
}
此代码编译但在运行时,正在给出空指针异常。
答案 0 :(得分:5)
MyBooks [3]的分配只分配数组你仍需要为数组中的每个条目分配一个“new MyBook()”。
答案 1 :(得分:2)
看看你的专栏:
Books [] myBooks = new Books[3];
你创建了一个数组,尽管数组中的每个元素都是一个空指针。
答案 2 :(得分:2)
看到它,您需要初始化数组中的每个元素,在for
或while
答案 3 :(得分:1)
这应该有效:
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);
}
}
}
}
答案 4 :(得分:0)
您需要将图书添加到数组中。这应该有效:
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;
}
}
}