我正在做一个拼写检查项目。我有一个单词列表,然后是葛底斯堡地址,其中一些单词拼写错误。我的工作是确定哪些单词拼写错误,然后在我打印地址时打印出拼写错误的单词下方的星号或其他内容。我的问题在 binarySearch 部分。我不确定语法,javadoc 看起来像中文。这是我的源代码(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;
}