我正在執行拼寫檢查項目。我有一個單詞列表,然後葛底斯堡的地址,有些單詞拼寫錯誤。我的工作是確定哪些單詞拼寫錯誤,然後在打印出地址時在拼寫錯誤的單詞下打印出星號或其他內容。我的問題是在binarySearch部分。我不確定的語法和javadoc看起來像它的中文。這裏是我的源代碼(binarySearch朝向底部)Java - binarySearch()。如何爲拼寫檢查設置二進制搜索
/*
* Assignment 1: Spell Check
* Professor Subrina Thompson
* CS102
*/
package spellcheck;
import java.util.*;
import java.io.*;
public class SpellCheck {
//48,219 words in the words.txt
//Declare Variables
static FileReader reader;
static Scanner input;
static ArrayList <String> wordList = new ArrayList<String>();
static FileReader reader2;
static Scanner input2;
static String testWord;
static String index;
//Main Method
public static void main(String[] args) throws FileNotFoundException {
fileSort();
}
//Open file to be read from
public static void openFile() throws FileNotFoundException {
reader = new FileReader("words.txt");
input = new Scanner(reader);
}
//sort the file
public static void fileSort() throws FileNotFoundException{
openFile();
//read the word list into an ArrayList
while (input.hasNext()){
wordList.add(input.next());
}
//Sort the array
Collections.sort(wordList);
}
//read the gettysburg address
public static void gAddress()throws FileNotFoundException{
reader2 = new FileReader("gettysburg.txt");
input2 = new Scanner(reader2);
//create loop to place word from file into a var then test to see if it is in the dictionary
for(int i = 0; i < wordList.size(); i++){
//place the word into a variable
testWord = input2.next();
//test if the word is in the dictionary
index = Collections.binarySearch(wordList,testWord);
}
}
//compare the address and array through binary search
//print out if spelling is correct
}
PS。我知道它並不完整,而且有很多鬆散的結局,但它仍然是一項進展中的工作。
編輯:
我試圖使基於關閉的binarySearch如何我明白工作的一個新的搜索功能。這是該函數的代碼。在 「列W」 將是字典中的單詞,從地址檢測對testWord:
公共靜態INT的binarySearch(列W){
int start = 0;
int stop = wordList.size() - 1;
while (start != stop){
int half = ((stop - start)/2) + start;
int res = wordList.get(half).compareToIgnoreCase(w);
if(res == 0){
return half;
}
else if(stop - start <= 1){
return -1;
}
else if(res > 0){
start = half;
}
else if(res < 0){
stop = half;
}
}
return -1;
}
他仍然會遇到我在回答中提出的問題 – 2013-02-13 23:46:23