[英]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";
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;
}
}
}
This code compiles but while runtime, its giving nullpointer exception. 该代码可以编译,但在运行时会给出nullpointer异常。
您对MyBooks [3]的分配仅分配了数组您仍然需要为数组中的每个条目分配一个“ new MyBook()”。
look at your line: 看你的台词:
Books [] myBooks = new Books[3];
you create an array, although every element in the array is a null pointer. 您创建了一个数组,尽管数组中的每个元素都是空指针。
看到它,你需要initializate你的阵列的elments的每一个,以尝试在一个for
或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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.