如何在java中使用SQL实现Interface Comparable,Collection.sort()?

时间:2017-05-01 18:46:21

标签: java database sorting comparator compareto

这是一个简单的图书馆项目。它必须通过要求用户根据关键字类型进行搜索来加载数据库中的数据。 我有两节课。其中一个是 Book类。

package library;

import java.sql.Date;

public class Book implements Comparable<Book> {

String title;
String author;
Date date;
String ISBN;
String format;
String publisher;
float price;
String[] keywords;
String[] inputArray;
String input;

public Book(String title_param, String author_param, java.util.Date date_param, String ISBN_param,
        String format_param, String publisher_param, float price_param, String keywords_param) {

    title = title_param;
    author = author_param;
    date = (Date) date_param;
    ISBN = ISBN_param;
    format = format_param;
    publisher = publisher_param;
    price = price_param;
    keywords = keywords_param.split(",");

}

public void setUserInput(String userIn) {
    input = userIn;
}

private int getRelevance(String userInput) {
    inputArray = userInput.split(",");
    int num = 0;

    for (int i = 0; i != keywords.length; i++) {
        String in = inputArray[i];

        for (int l = 0; l != keywords.length; l++) {
            if (in.equals(keywords[l]))
                num++;
        }
    }

    return num;
}

public int compareTo(Book o) {
    if (this.getRelevance(input) > o.getRelevance(input)) {
        return 1;
    } else if (this.getRelevance(input) < o.getRelevance(input)) {
        return -1;
    }

    return 0;
}
}

在第二个中,我想以正确的方式调用Collection.sort()和CompareTo(),以便显示包含至少一个这些关键字的书籍。但是它必须在输入上显示具有最多关键字的顶部书籍。 收集和比较部分 现在不行。

    package library;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Scanner;

public class LibrarySearch {
    static ArrayList<Book> books = new ArrayList<Book>();
    ArrayList<LibrarySearch> genres = new ArrayList<LibrarySearch>();
    static ArrayList<LibrarySearch> keywords = new ArrayList<LibrarySearch>();

    public static void main(String[] args) {
        load_data();
    }

    private static void load_data() {
        Collections.sort(books, new Comparator<Book>() {
            @Override
            public int compare(Book first, Book second) {
                if (first.compareTo(second) == 1) {
                    return 1;
                } else if (first.compareTo(second) == -1) {
                    return -1;
                }
                return 0;

            }
        });

        Connection connection = null;
        Statement statement = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "123456");
            statement = connection.createStatement();
            System.out.println("Choose to search by keywords or genres");
            Scanner scanner = new Scanner(System.in);
            String input = scanner.nextLine();

            if (input.equals("keywords")) {
                System.out.println("Enter your keywords: ");
                String[] keyWordsInput = scanner.nextLine().split(",");
                ResultSet result = null;

                for (int i = 0; i != keyWordsInput.length; i++) {
                    result = statement
                            .executeQuery(" SELECT * FROM book WHERE keywords LIKE '%" + keyWordsInput[i] + "%'");
                }

                while (result.next()) {
                    int id = result.getInt("id");
                    String title = result.getString("title");
                    String author = result.getString("author");
                    Date date = result.getDate("date");
                    String ISBN = result.getString("ISBN");
                    String format = result.getString("format");
                    String publisher = result.getString("publisher");
                    float price = result.getFloat("price");
                    String keywords = result.getString("keywords");

                    System.out.println("ID = " + id);
                    System.out.println("TITLE = " + title);
                    System.out.println("AUTHOR = " + author);
                    System.out.println("DATE = " + date);
                    System.out.println("ISBN = " + ISBN);
                    System.out.println("FORMAT = " + format);
                    System.out.println("PUBLISHER = " + publisher);
                    System.out.println("PRICE = " + price);
                    System.out.println("KEYWORDS = " + keywords);
                    System.out.println("___________________________________________________________________________");

                    if (title.equals("I,Robot")) {
                        Book new_book = new Book(title, author, date, ISBN, format, publisher, price, keywords);
                        books.add(new_book);
                    }
                    if (title.equals("Catch-22")) {
                        Book new_book1 = new Book(title, author, date, ISBN, format, publisher, price, keywords);
                        books.add(new_book1);
                    }
                    if (title.equals("Pride and Prejudice")) {
                        Book new_book2 = new Book(title, author, date, ISBN, format, publisher, price, keywords);
                        books.add(new_book2);
                    }
                    if (title.equals("Gone with the Wind")) {
                        Book new_book3 = new Book(title, author, date, ISBN, format, publisher, price, keywords);
                        books.add(new_book3);
                    }

                }
                result.close();
                statement.close();
                connection.close();

            } else if (input.equals("genres")) {
                System.out.println("Enter your genres" + ": ");

                String genresInput = scanner.nextLine();
                ResultSet result = statement.executeQuery(
                        " SELECT * FROM books_genres JOIN book ON (book.id = books_genres.book_id) JOIN genre ON (genre.id = books_genres.genre_id) WHERE name LIKE '%"
                                + genresInput + "%' ");
                while (result.next()) {
                    int id = result.getInt("id");
                    String name = result.getString("name");

                    int book_id = result.getInt("book_id");
                    int genre_id = result.getInt("genre_id");

                    int id1 = result.getInt("id");
                    String title = result.getString("title");
                    String author = result.getString("author");
                    Date date = result.getDate("date");
                    String ISBN = result.getString("ISBN");
                    String format = result.getString("format");
                    String publisher = result.getString("publisher");
                    float price = result.getFloat("price");
                    String keywords = result.getString("keywords");

                    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

                    System.out.println("Book ID = " + id1);
                    System.out.println("TITLE = " + title);
                    System.out.println("AUTHOR = " + author);
                    System.out.println("DATE = " + date);
                    System.out.println("ISBN = " + ISBN);
                    System.out.println("FORMAT = " + format);
                    System.out.println("PUBLISHER = " + publisher);
                    System.out.println("PRICE = " + price);
                    System.out.println("KEYWORDS = " + keywords);

                    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

                    System.out.println("Genre ID = " + id);
                    System.out.println("Genre Name = " + name);

                    System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");

                    System.out.println("Book ID = " + book_id);
                    System.out.println("Genre ID = " + genre_id);

                }

                result.close();
                statement.close();
                connection.close();
            }

            else {
                System.out.println("Sorry, wrong command");
            }

        } catch (SQLException ex) {
            System.out.println("No successful connection");
            System.out.println("SQLException: " + ex.getMessage());
            System.out.println("SQLState: " + ex.getSQLState());
        }

        catch (ClassNotFoundException x_not_found) {
            System.out.println("Class not found");
        }
    }

}

2 个答案:

答案 0 :(得分:0)

首先,由于getRelevance()方法返回int,我建议像这样编写compareTo:

public int compareTo(Book o) {
    return this.getRelevance(input) - o.getRelevance(input);
}

同样,比较器看起来像这样:

Collections.sort(books, new Comparator<Book>() {
    @Override
    public int compare(Book first, Book second) {            
        return first.compareTo(second);
    }
});

至于调用,看起来好像是先排序空列表,然后用搜索结果填充它。我建议将排序部分移动到load_data()方法的末尾。

答案 1 :(得分:0)

一个问题:您正在迭代inputArray keywords.length次,这可能不正确。不知道这是不是你的问题 - 可能是关键字数组比输入数组短得多。

更大的问题是迭代inputArray元素的关键字。将您的关键字放在HashSet中并测试包含。