2017-05-01 2 views
0

Das ist ein einfaches Bibliotheksprojekt. Es muss die Daten aus der Datenbank laden, indem der Benutzer aufgefordert wird, basierend auf Schlüsselwörter oder Genres zu suchen. Ich habe zwei Klassen. Einer von ihnen ist die Buchklasse .:Wie Schnittstelle vergleichbar implementieren, Collection.sort() mit SQL in Java?

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

In der zweiten, den ich in der richtigen Weise Collection.sort() und CompareTo(), in einer Weise, die angerufen werden soll, dass es zeigt die Bücher, die mindestens eines dieser Schlüsselwörter enthalten. ABER es muss die Bücher oben zeigen, die die meisten Schlüsselwörter von der Eingabe haben. Die Sammlung und die Vergleichsteile funktionieren NICHT gerade.

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

} 
+0

Sie wissen, wie Sie "Comparable " implementieren, da Ihr 'Book' es implementiert. Was ist deine Frage? Was ist das Problem? Bitte seien Sie ausführlicher, sonst können wir Ihnen nicht helfen. – Turing85

+0

Es funktioniert nicht, ich könnte es nicht richtig nennen, denke ich. Danke – Geya

+0

"Es funktioniert nicht." -> Was ist "es"? Wie ich schon sagte: Bitte sei etwas ausführlicher. Welche Teile funktionieren? Welche Teile funktionieren nicht? Aus dem Blick auf Ihre Frage kann ich nicht ableiten, ob Sie ein konzeptionelles Problem haben, Probleme mit der Datenbankverbindung, Probleme beim Sortieren, einige von ihnen oder alle. A [MCVE] (https://stackoverflow.com/help/mcve) würde ebenfalls geschätzt werden. – Turing85

Antwort

0

First off, da getRelevance() Methode int zurückgibt, würde ich vorschlagen, compareTo wie dieses schreiben:

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

Ähnlich Komparator würde wie folgt aussehen:

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

Was Anrufen, sieht so aus, als würden Sie die leere Liste zuerst sortieren und dann mit Suchergebnissen füllen. Ich schlage vor, den sortierenden Teil an das Ende der Methode load_data() zu verschieben.

0

Ein Problem: Sie iterieren über inputArraykeywords.length mal, was wahrscheinlich nicht korrekt ist. Ich weiß nicht, ob das Ihr Problem ist - vielleicht, wenn das Array der Schlüsselwörter viel kürzer ist als das Eingabe-Array.

Das größere Problem iteriert über Schlüsselwörter für jedes Element von inputArray. Setzen Sie Ihre Keywords in ein HashSet und testen Sie stattdessen auf contains.

Verwandte Themen