我被要求编写一种方法,该方法接收扫描器,并返回一个排序的单词数组,该单词数组仅包含字母,没有重复(且长度不超过3000)。然后,我被要求编写一个方法来检查给定的词汇表中是否包含某个给定的字符串。我使用了一种简单的二进制搜索方法。 这就是我所做的:
public static String[] scanVocabulary(Scanner scanner){
String[] array= new String[3000];
int i=0;
String word;
while (scanner.hasNext() && i<3000) {
word=scanner.next();
if (word.matches("[a-zA-Z]+")){
array[i]=word.toLowerCase();
i++;
}
}int size=0;
while (size<3000 && array[size]!=null ) {
size++;
}
String[] words=Arrays.copyOf(array, size);
if (words.length==0 || words.length==1) {
return words;
}
else {
Arrays.sort(words);
int end= removeDuplicatesSortedArr(words);
return Arrays.copyOf(words, end);
}
}
private static int removeDuplicatesSortedArr(String[] array) { //must be a sorted array. returns size of the new array
int n= array.length;
int j=0;
for (int i=0; i<n-1; i++) {
if (!array[i].equals(array[i+1])) {
array[j++]=array[i];
}
}
array[j++]=array[n-1];
return j;
}
public static boolean isInVocabulary(String[] vocabulary, String word){
//binary search
int n=vocabulary.length;
int left= 0;
int right=n-1;
while (left<=right) {
int mid=(left+right)/2;
if (vocabulary[mid].equals(word)){
return true;
}
else if (vocabulary[mid].compareTo(word)>0) {
right=mid-1;
}else {
right=mid+1;
}
}
return false;
}
尝试以下代码时:
public static void main(String[] args) {
String vocabularyText = "I look at the floor and I see it needs sweeping while my guitar gently weeps";
Scanner vocabularyScanner = new Scanner(vocabularyText);
String[] vocabulary = scanVocabulary(vocabularyScanner);
System.out.println(Arrays.toString(vocabulary));
boolean t=isInVocabulary(vocabulary, "while");
System.out.println(t);
System.out.println("123");
}
我什么都没得到-
[and, at, floor, gently, guitar, i, it, look, my, needs, see, sweeping, the, weeps, while]
没有其他内容打印出来或退回。这两个函数似乎分别可以正常工作,所以我不会弄错我在做的事情。 我很高兴听到您的想法,在此先感谢:)
答案 0 :(得分:1)
这与控制台无关。您的isInVocabulary
方法正在此块中进入无限循环:
if (!isInVocabulary(vocabulary, "while")) {
System.out.println("Error");
}
如果您要通过isInVocabulary
进行调试,则会看到while循环经过几次迭代后,
left = 0;
right = 2;
mid = 1;
if (vocabulary[mid].equals(word)){
// it doesn't
} else if (vocabulary[mid].compareTo("while") > 0) {
// it doesn't
} else {
right = mid + 1;
// this is the same as saying right = 1 + 1, i.e. 2
}
所以你会永远循环。