我正在开发一个图书馆管理程序(这是一个在线课程的任务),并且我无法在运行时解决nullpointerexception错误。Java初学者:nullpointerexception错误
这也是迄今为止该程序:
//file Library.java
public class Library {
String address;
Book[] collection;
int collectionCounter = 0;
// Add the missing implementation to this class
public static void main(String[] args)
{
// Create two libraries
Library firstLibrary = new Library("10 Main St.");
Library secondLibrary = new Library("228 Liberty St.");
// Add four books to the first library
firstLibrary.addBook(new Book("The Da Vinci Code"));
firstLibrary.addBook(new Book("Le Petit Prince"));
firstLibrary.addBook(new Book("A Tale of Two Cities"));
firstLibrary.addBook(new Book("The Lord of the Rings"));
}
//Constructor
public Library(String libraryName)
{
address = libraryName;
collectionCounter = 0;
}
//Methods
public void addBook(Book newBook)
{
System.out.println(this.collectionCounter);
this.collection[this.collectionCounter] = newBook;
this.collectionCounter += 1;
}
而其他java文件,为Book
类:
public class Book {
String title;
boolean borrowed;
// Creates a new Book
public Book(String bookTitle) {
// Implement this method
title = bookTitle;
borrowed = false;
}
// Marks the book as rented
public void rented() {
// Implement this method
this.borrowed = true;
}
// Marks the book as not rented
public void returned() {
// Implement this method
this.borrowed = false;
}
// Returns true if the book is rented, false otherwise
public boolean isBorrowed() {
// Implement this method
return this.borrowed;
}
// Returns the title of the book
public String getTitle() {
return this.title;
}
public static void main(String[] arguments) {
// Small test of the Book class
Book example = new Book("The Da Vinci Code");
System.out.println("Title (should be The Da Vinci Code): " + example.getTitle());
System.out.println("Borrowed? (should be false): " + example.isBorrowed());
example.rented();
System.out.println("Borrowed? (should be true): " + example.isBorrowed());
example.returned();
System.out.println("Borrowed? (should be false): " + example.isBorrowed());
}
}
这是程序的输出:
0
Exception in thread "main" java.lang.NullPointerException
at Library.addBook(Library.java:59)
at Library.main(Library.java:14)
我明白这个错误是由一系列书引起的,但我真的不知道该怎么做,我从来没有见过一个对象实例化作为一个方法的参数。提前致谢!
当人们发布答案一秒钟之前,你可以......正是我要说的xD(除此之外,我不明白为什么你会在这里使用LinkedList而不是ArrayList) 。 – bcsb1001
打我吧:) –
嘿,谢谢你的回答,当你说'addBook'可以看起来像这四行代码,你的意思是,如果我选择链表或者它的工作方式阵列方法呢? – Frank