0

这最终将允许用户通过使用两位数来查找书籍。但是,只有在您输入正确的数字时才会输出标题。有关写入重要信息的代码的详细信息...

基本上,您输入的数字(refNum)与二进制搜索数组的预定值正确匹配的程序的总和......将输出书名。

   class books {

        String refNum, title;

        books (String _refNum, String _title) {
            refNum = _refNum = enterNumberField.getText(); //grab inputted #(continues...)

(续)与存储在数组中的数字进行比较,# 必须等于 binarySearch 数组中的 # ,如果相等,将正确输出标题。Aka reNum = 4 (也是 binarySearch[0]) 必须等于 title[0] 才能输出“Harry Potter”

            int refNum[] = new int[2];

            refNum[0] = 4;
            refNum[1] = 6;
            refNum[2] = 10;

            int binarySearch[] = new int[2];

            binarySearch[0] = 4;
            binarySearch[1] = 6;
            binarySearch[2] = 10;

            String title[] = new String[2];

            title[0] = "Harry Potter";
            title[1] = "Chrysalids";
            title[2] = "Lord of the Flies";
       }
   }

这将用于二进制搜索,因为它使用输入的数字来查找它是否与任何内容匹配,如果匹配,则输出相应的标题。

public static Boolean binarySearch(String [ ] A, int left, int right, String V){
         int middle;
         refNum ++;
         if (left > right) {
             return false;
         }

         middle = (left + right)/2;
         int compare = V.compareTo(A[middle]);
         if (compare == 0) {
             return true;
         }
         if (compare < 0) {
             return binarySearch(A, left, middle-1, V);
         } else {
             return binarySearch(A, middle + 1, right, V);
         }
     }

最终我将添加输出此代码的代码,但首先我需要学习如何在类和实际搜索中组织数组,希望我已经以您理解我的目标的方式解释了这一点......所以有什么想法吗?

4

2 回答 2

1

通常,您应该避免在一个类中使用具有相等索引的多个数组。这是由一系列书籍完成的:

public class Book {
  private int refNum;
  private String name;

  public Book(int refNum, String name) {
    this.refNum = refNum;
    this.name = name;
  }

  public int getRefNum() {
    return refNum;
  }

  public void setRefNum(int refNum) {
    this.refNum = refNum;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }
}

// a comparator allows ordering to an arbitrary row
public RefNumOrder implements Comparator<Book> {
  public int compare(Book b1, Book b2) {
    return b1.getRefNum() - b2.getRefNum();
  }
}

public class Books {
  private List<Book> books = new ArrayList<Book>();
  public Books() {
     books.add(new Book(..);
     ..
  }
  public Book getByRefNum( int refNum) {
    Collections.sort(books, new RefNumOrder());
    int index =  Collections.binarySearch(book, new RefNumOrder());
    if (index >= 0) return books.get(index);
    return null;
  }
}

这样,您可以轻松查找任何行,而无需处理多个数组。

于 2013-05-21T22:43:07.943 回答
0

您知道,您可以只使用地图并进行查找。

于 2013-05-22T05:28:59.327 回答