I am geting a null pointer exception when i try to run this method, the goal is to populate the booklist object array but not over 3 objects. The error occurs when i set 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;
You need ArrayList instead of array
ArrayList<Book> booklist = new ArrayList<Book>();
public boolean borrowBook(Book b){
if(booklist.size() == 0){
booklist.add(b);
System.out.println(this.name+" has successfully borrowed "+b);
return true;
}
if(booklist.size() < 3){ //I'm not sure what you are trying to achieve here
booklist.add(booklist.size(), 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With