【发布时间】:2021-08-22 17:06:43
【问题描述】:
我有一本书课:
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");
}
}
我有一个 LibraryDatabase 类,它有一个包含两个 Book 对象的 ArrayList:
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;
}
}
我想让用户选择他们想要的类型,并让控制台打印出所有具有该类型作为属性的对象。 我在一个单独的类中有这个方法:
public void showTitles() {
LibraryDatabase libraryDatabase = new LibraryDatabase();
Scanner kbMeter = new Scanner(System.in);
String genre = kbMeter.nextLine();
if (genre.equals(libraryDatabase.getBookGenre())) {
//???
}
}
我不知道在 if 语句中放什么才能打印出具有该类型的所有对象。感谢您的帮助。
【问题讨论】:
标签: java oop if-statement arraylist