public class Library{
private ArrayList<Book> bookList = new ArrayList<Book>();
public ArrayList<Book> viewBooksByAuthor(String author ){
ArrayList<Book> b =new ArrayList<Book>();
for(Book bl:bookList){
if(bl.getAuthor().equals(author)){
b.add(bl);
}
return b;
}
return b;
}
}
public class Main{
public static void main (String[] args) {
System.out.println("Enter the author name:");
String auth=sc.next();
ArrayList<Book> ba=l.viewBooksByAuthor(auth);
if(ba.isEmpty()){
System.out.println("None of the book published by the author "+auth);
}
else{
for(Book an:ba){
System.out.println("ISBN no: "+an.getIsbnno());
System.out.println("Book name: "+an.getBookName());
System.out.println("Author name: "+an.getAuthor());
}
}
}
我有两个类Book.java和Library.java,我想实现viewAllBooks()方法,在该方法中,我将作者姓名作为参数传递,该方法将返回一个ArrayList,其中将包含该作者的所有书籍名称,但是如果我添加两本书与同一位作者,但我没有得到正确的输出,那么在搜索作者姓名后,我只会得到一本书的详细信息,我该如何解决?
答案 0 :(得分:1)
在viewBooksByAuthor
中,在for循环中有一个return语句,它将在第一次迭代后立即退出函数。删除内部return语句(但保留外部return语句)可以解决您的问题。