Search code examples
javabluej

How to return the textbook so it is not set to null?


I'm still new to Java, currently using BlueJ.

The first method is from class Library and works fine:

public TextBook borrowBook(LibraryCard card){

    TextBook book = null;
    if ( (nextBook < bookShelf.length)  && !card.expired() ) {
        book = bookShelf[ nextBook ];
        bookShelf[ nextBook ] = null;
        nextBook++;
        card.swipe();
    }
    return book;
}

The second is from class Student and I can not figure out how to change book from null to the book taken off the bookshelf( an array of TextBook objects):

public void study()
{
    if( book == null ){
          library.borrowBook(card);
          return book;
    }            
    else{
        if( !book.isFinished() ){
          book.readNextChapter();
        }
        else{
          library.returnBook(book);
        }
    }

}

Solution

  • public void study()
    {
        if( book == null ){
              library.borrowBook(card);
              return book;
        }            
        else{
            if( !book.isFinished() ){
              book.readNextChapter();
            }
            else{
              library.returnBook(book);
            }
        }
    
    }
    

    First of all, the return type of the function is void hence your function should not return anything. Currently there is a return book in your function.

    Now correct me if I'm wrong. I think this is what you want to achieve:

    public void study() {
        if(book == null) {
            book = library.borrowBook(card);
        } else {
            if(!book.isFinished()) {
                book.readNextChapter();
            } else {
                library.returnBook(book);
            }
        }
    }
    

    Since library.borrowBook(card); returns the borrowed book, just assign it to book. Also, always write clean code (correct indention, consistent position of curly braces, and, remove unnecessary spaces, and etc...). Clean code is good code. I hope this helps!