您好,我制作的程序需要一系列"条款"每个都有自己的权重(Long值)和查询(String值)。它应该从.txt文件中获取许多术语,并将它们初始化为私有"术语"数组,然后它使用arrays.sort按字典顺序重新排列他们的查询。 Term [] allmatches(字符串前缀)函数旨在利用二进制搜索在已经按字典顺序排序的条款中查找" Terms"第一个匹配开始和最后一个匹配结束的数组(我确信我的prefixOrder比较器和我的二进制搜索方法可以自行运行)。然后使用" for"循环,我尝试将所有这些特定术语复制到一个名为" newterms的新数组中。"问题是我只返回" null"值。
public class Autocomplete {
private Term[] terms;
/**
* Initializes the data structure from the given array of terms.
* @param terms a collection of terms.
*/
public Autocomplete(Term[] terms) {
if (terms == null) {
throw new java.lang.NullPointerException(); }
this.terms = terms;
Arrays.sort(terms);
}
/**
* Returns all terms that start with the given prefix, in descending order
* of weight.
* @param prefix term prefix.
* @return all terms that start with the given prefix, in descending order
* of weight.
*/
public Term[] allMatches(String prefix) {
if (prefix == null) {
throw new java.lang.NullPointerException(); }
Term term = new Term(prefix);
Comparator<Term> prefixOrder = Term.byPrefixOrder(prefix.length());
int a = BinarySearchDeluxe.firstIndexOf(this.terms, term, prefixOrder);
int b = BinarySearchDeluxe.lastIndexOf(this.terms, term, prefixOrder);
int c = a;
Term[] newterms = new Term[b - a];
for (int i = 0; i > b - a; i++) {
newterms[i] = this.terms[c];
c++;
}
Arrays.sort(newterms, Term.byReverseWeightOrder());
return newterms;
}
这是&#34;测试&#34;我正在使用的客户:
public static void main(String[] args) {
String filename = args[0];
In in = new In(filename);
int N = in.readInt();
Term[] terms = new Term[N];
for (int i = 0; i < N; i++) {
long weight = in.readLong();
in.readChar();
String query = in.readLine();
terms[i] = new Term(query, weight);
}
int k = Integer.parseInt(args[1]);
Autocomplete autocomplete = new Autocomplete(terms);
while (StdIn.hasNextLine()) {
String prefix = StdIn.readLine();
Term[] results = autocomplete.allMatches(prefix);
for (int i = 0; i < Math.min(k, results.length); i++) {
StdOut.println(results[i]);
}
}
}
我在这里做错了什么?非常感谢帮助,谢谢。
答案 0 :(得分:1)
allMatches(String prefix)
中的for循环有一个错误的布尔谓词,而不是
for (int i = 0; i > b - a; i++)
应该是
for (int i = 0; i < b - a; i++)