There are similar questions asked on Stack Overflow but I still could not find a solution. I am creating a simple system information prototype for a Library.
How do I make my program have search functionality? The methods in the Library class are supposed to return the list of books that match the given title, publisher or year. Also, the method(s) need to return an arraylist. Here is what I have so far.
public class Book {
private String title;
private String publisher;
private int year;
public Book(String title, String publisher, int year) {
this.title = title;
this.publisher = publisher;
this.year = year;
}
public String title() {
return this.title;
}
public String publisher() {
return this.publisher;
}
public int year() {
return this.year;
}
public String toString() {
return this.title + ", " + this.publisher + ", " + this.year;
}
}
import java.util.ArrayList;
public class Library {
private ArrayList<Book> list;
public Library() {
this.list = new ArrayList<Book>();
}
public void addBook(Book newBook) {
list.add(newBook);
}
public void printBooks() {
for (Book boo : this.list) {
System.out.println(boo);
}
}
public ArrayList<Book> searchByTitle(String title) {
ArrayList<Book> found = new ArrayList<Book>
for (Book title : found) {
if (title.contains(title.title())) {
return title;
}
}
return found;
}
public ArrayList<Book> searchByPublisher(String publisher) {
ArrayList<Book> found = new ArrayList<Book>
//similar code to the other ArrayList method
return found;
}
public ArrayList<Book> searchByYear(String year) {
ArrayList<Book> found = new ArrayList<Book>
//similar code to the other ArrayList method
return found;
}
}
public class Main {
public static void main(String[] args) {
Library Library = new Library();
Library.addBook(new Book("Cheese Problems Solved", "Woodhead Publishing", 2007));
Library.addBook(new Book("The Stinky Cheese Man and Other Fairly Stupid Tales", "Penguin Group", 1992));
Library.addBook(new Book("NHL Hockey", "Stanley Kupp", 1952));
Library.addBook(new Book("Battle Axes", "Tom A. Hawk", 1851));
ArrayList<Book> result = Library.searchByTitle("Cheese");
for (Book Book: result) {
System.out.println(Book);
}
System.out.println("---");
for (Book Book: Library.searchByPublisher("Penguin Group ")) {
System.out.println(Book);
}
System.out.println("---");
for (Book Book: Library.searchByYear(1851)) {
System.out.println(Book);
}
}
}