vendredi 4 juin 2021

How do I print one or multiple objects from an ArrayList with a particular attribute?

I have a Book class:

public class Book {
    public String title;
  
    public  String author;

    public  int genre;
    
    public Book(){}
  
    public Book(String title, String author, int genre) {
        this.title = title;
        this.author = author;
        this.genre = genre;
    }
  

    public String getBookTitle() {
        return  title;
    }
    
    public String getBookAuthor() {
        return author;
    }
    
    public String getBookGenre() {
        if (genre == 1) {
          return ("Fantasy");
        }
        else if (genre == 2) {
          return ("Science Fiction");
        }
        else if (genre == 3) {
          return ("Dystopian");
        }
        return "genre";
        
    }

    @Override
    public String toString() {
        return ("Title: " + this.getBookTitle() + " \nAuthor: " + this.getBookAuthor() + " \nGenre: " + this.getBookGenre() + "\n");
    }
    
}

And I have a LibraryDatabase class that has an ArrayList of two Book objects:

import java.util.*;
public class LibraryDatabase extends Book {
  List<Book> bookDatabase = new ArrayList<>();

  public LibraryDatabase() {
      super();
  }

  public List<Book> books() {
    Book book1 = new Book("Harry Potter", "J.K. Rowling", 1);
    Book book2 = new Book("Neuromancer", "William Gibson", 2);

    bookDatabase.add(book1);
    bookDatabase.add(book2);
    return bookDatabase;
  }
}

I want to allow the user to choose which genre they would like and have the console print out all objects that have that genre as an attribute. I have this method in a separate class:

public void showTitles() {
    LibraryDatabase libraryDatabase = new LibraryDatabase();
    Scanner kbMeter = new Scanner(System.in);
    String genre = kbMeter.nextLine();
    if (genre.equals(libraryDatabase.getBookGenre())) {
      //???
    }

  }

I don't know what to put inside the if statement in order to print out all objects with that genre. Thanks for the help.

Aucun commentaire:

Enregistrer un commentaire