缺少返回语句方法返回副本



我已经创建了这个方法,我不确定为什么它说缺少一个返回语句。 我需要将打印更改为退货吗?(这是最底部的方法)我有点 Java 初学者,所以任何帮助将不胜感激!

public class Book {
private String title;
private String author;
private int copies;
private boolean borrowed;

public Book( String inAuthor, String inTitle, int inNumberOfCopies ) {
    this.author = inAuthor;
    this.title = inAuthor;
    this.copies = inNumberOfCopies;
}
 public void borrowed() {
    borrowed = true;
}
public void rented() {
    borrowed = true;
}
public void returned() {
    borrowed = false;
}
public boolean isBorrowed() {
    return borrowed;
}
public String getAuthor() {
    return this.author;
}
public static String getTitle() {
    return getTitle();
}
public int getTotalCopies() {
    return this.copies;
}
public int getAvailableCopies() {
}
public void withdrawCopy() {
        int found = 0;
for (Book b : Library.getListOfBooks()) {
    if (b.getTitle().equals(title)) {
       if (found == 0) {
        found = 1;
    }
    if (!b.isBorrowed()) {
        b.borrowed=true;
        found = 2;
        break;      
        }
     if (found == 0) {
        System.out.println("Sorry, this book is not in our catalog.");
    } else if (found == 1) {
        System.out.println("Sorry, this book is already borrowed.");
    } else if (found == 2) {
        System.out.println("You successfully borrowed " + title);
    }
    }
    }
}
public String returnCopy() {
    boolean found = false;
    for (Book book : Library.getListOfBooks()) {
        if (getTitle().equals(title) && book.isBorrowed()) {
            book.returned();
            found = true;
        }
        if (found) {
        System.out.println("you successfully returned " + title);
    }
    }
}
}
public String returnCopy()

String public 之后表示此方法将返回一个String 。您的public String returnCopy()当前未返回任何内容。

如果您不想返回任何内容,可以使用如下void

public void returnCopy(){
    // code
}

public int getAvailableCopies() 同样的问题,这应该返回一个int但你没有返回任何东西。

小心:

此方法:

public static String getTitle() {
    return getTitle();
}

是一种没有基本条件的递归方法。这将导致错误并强制应用程序崩溃。

您已将方法定义为返回String但不返回方法主体中的任何位置的值。最简单的解决方法可能是将返回类型更改为void...

public void returnCopy() {...
}

上面的所有答案都指向同一个问题,你已经定义了破坏关于它们返回内容的合同的方法。

在你的代码中,你也有这样的东西:

public int getAvailableCopies() {
}

所以你告诉编译器,你有一个名为getAvailableCopyies的方法,它不需要参数返回一个整数

但是如果你不返回任何东西,那么你就违背了你自己的方法,你自己的合约,这足以让编译器抱怨......


结论:

请记住定义方法的信息。

最新更新