简体   繁体   中英

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());
                            }
                        }

    }

I have two classes Book.java and Library.java i want to implement the viewAllBooks() method in which i am passing the author name as an argument and the method will return an ArrayList which will contain all the books with that author name but i am not getting the proper output if i add 2 books with same author then after searching for author name i only get one book details how can i fix that?

In viewBooksByAuthor there is a return statement inside the for loop which will exit your function immediately after the first iteration. Drop the inner return statement (but keep the outer) may solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM