Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with object array

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;
like image 759
Tolkingdom Avatar asked Aug 31 '26 19:08

Tolkingdom


1 Answers

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;
}
like image 200
DnR Avatar answered Sep 02 '26 11:09

DnR