首页 > 解决方案 > 检查对象特定值的对象数组列表

问题描述


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 ,其中将包含具有该作者姓名的所有书籍,但我如果我添加 2 本书与同一作者,则没有得到正确的输出,然后在搜索作者姓名后,我只能得到一本书的详细信息,我该如何解决?

标签: java

解决方案


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


推荐阅读