簡體   English   中英

檢查對象特定值的對象數組列表

[英]Arraylist of objects checking specific values of an object


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 本作者相同的書,則無法獲得正確的輸出,然后在搜索作者姓名后,我只得到一本書的詳細信息,我該如何解決?

viewBooksByAuthor ,for 循環中有一個 return 語句,它將在第一次迭代后立即退出您的函數。 刪除內部 return 語句(但保留外部)可能會解決您的問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM