gpt4 book ai didi

java - 对象的数组列表检查对象的特定值

转载 作者:行者123 更新时间:2023-12-02 09:03:11 26 4
gpt4 key购买 nike


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,其中包含该作者的所有书籍名称,但如果我添加同一作者的两本书,然后在搜索作者姓名后我只得到一本书的详细信息,我无法获得正确的输出,我该如何解决这个问题?

最佳答案

viewBooksByAuthor 中,for 循环内有一个 return 语句,它将在第一次迭代后立即退出函数。删除内部 return 语句(但保留外部)可能会解决您的问题。

关于java - 对象的数组列表检查对象的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60017830/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com