如何在一个类中组织多个数组?

时间:2013-05-21 22:32:03

标签: java class

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

基本上,你输入一个数字(refNum)的程序的总和正确地匹配到binarySearch数组的预定值...将输出书名。

   class books {

        String refNum, title;

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

(续)比较  如果数字存储在数组中,则#必须等于二进制搜索数组中的#,如果相等,则为  适当的输出标题。 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);
         }
     }

最终我将添加输出此代码的代码,但首先我需要学习如何在类和实际搜索中组织数组,希望我以一种你理解我的目标的方式解释这个...所以任何想法?

2 个答案:

答案 0 :(得分: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;
  }
}

通过这种方式,您可以轻松查找任何行,而无需处理多个数组。

答案 1 :(得分:0)

你知道,你可以使用Map并进行查找。