如何return教科书不设置为null?

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

我还是 Java 的新手,目前正在使用 BlueJ。

第一种方法来自 class 库并且工作正常:

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

第二个来自 class 学生,我不知道如何将书从 null 更改为从书架上取下的书(TextBook 对象数组):

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

}

根据资料,我有...

您可能有一个 Main class,其中正在执行操作。

在下列情况下,该书(教科书)将为空:

  • 如果nextbook > bookshelf.length
  • card 已过期

基本上,方法不会进入“if”大括号和 returns null。

希望对您有所帮助!

你的 study 方法有问题你在 study 方法中 returning 一个对象,它是一个 void 方法,这将导致编译错误。

假设您要将 book 变量分配给 library.borrowBook(card) 的 return 值,那么您需要分配类似 book=library.borrowBook(card) 并删除 return声明。

所以你的代码应该如下所示。

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

}

首先,函数的 return 类型是 void 因此你的函数不应该 return 任何东西。当前您的函数中有一个 return book

如果我错了,请纠正我。我认为这就是您想要实现的目标:

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

既然library.borrowBook(card);return是借来的书,就分配给book。此外,始终编写干净的代码(正确的缩进、大括号的一致位置以及删除不必要的空格等)。干净的代码是好的代码。希望对您有所帮助!