当我尝试运行此方法时,出现了空指针异常,目标是填充书本对象数组,但不超过3个对象。当我设置booklist [0] = b时发生错误
private Book [] booklist;
public boolean borrowBook(Book b)
{
if(booklist == null)
{
booklist[0] = b;
System.out.println(this.name+" has successfully borrowed "+b);
return true;
}
if(booklist.length < 3)
{
booklist[booklist.length] = b;
System.out.println(this.name+" has successfully borrowed "+b);
return true;
}
System.out.println(this.name+" has reached the borrowing limit! Return those books "+this.name);
return false;
最佳答案
试试这个。
private Book [] booklist;
public boolean borrowBook(Book b) {
if (booklist == null) {
booklist = new Book[3];
booklist[0] = b;
return true;
}
for (int i = 0; i < booklist.length; i++) {
if (booklist[i] == null) {
booklist[i] = b;
return true;
}
}
return false;
}
public static void main(String[] args) {
Book caller = new Book();
System.out.println(caller.borrowBook(new Book()));
System.out.println(caller.borrowBook(new Book()));
System.out.println(caller.borrowBook(new Book()));
System.out.println(caller.borrowBook(new Book()));
}
关于java - 对象数组出现问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26133031/