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;

Answers


Try this.

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()));
}

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;
}

Need Your Help

PHP script results 500 Internal server error

php mysql

I can't understand why this PHP script gives me 500 internal server error.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.