我试图创建一个方法来返回来自不同类的对象。
例如:
public Book searchTitle(String title) {
for (Book book : library) {
if (book.getTitle().equals(title)) {
return book;
}
}
// If the book is not found, I have no return and the program won't compile.
//How do I make the method work in the case that the book is not found?
答案 0 :(得分:4)
如果找不到null
,则返回Book
或抛出异常:
public Book searchTitle(String title) {
for (Book book : library) {
if (book.getTitle().equals(title)) {
return book;
}
}
return null;
}