在系统信息原型中创建搜索功能

时间:2015-01-14 16:28:09

标签: java search arraylist

在Stack Overflow上有类似的问题,但我仍然找不到解决方案。我正在为图书馆创建一个简单的系统信息原型 如何让我的程序具有搜索功能? Library类中的方法应该返回与给定标题,发布者或年份匹配的书籍列表。此外,该方法需要返回一个arraylist。这是我到目前为止所拥有的。

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

1 个答案:

答案 0 :(得分:2)

你是正确的方式。只需将找到的书籍添加到结果列表中:

public ArrayList<Book> searchByTitle(String title) {
    ArrayList<Book> found = new ArrayList<Book>();

    for (Book book : found) {
        if (book.title().contains(title)) {
            found.add(book);
        }
    }
    return found;
}

我还纠正了你在代码安宁方面遇到的一些错误。你的其他代码似乎充满了其他错误,我在这里没有解决。您可能想要了解有关Java语法的更多信息。

修改

正如威格尔斯先生指出的那样,你可能想要一个不区分大小写的搜索。请参阅How to check if a String contains another String in a case insensitive manner in Java?