gpt4 book ai didi

Java - 二进制搜索()。如何为拼写检查设置 binarySearch

转载 作者:行者123 更新时间:2023-11-29 08:00:14 25 4
gpt4 key购买 nike

我正在做一个拼写检查项目。我有一个单词列表,然后是葛底斯堡地址,其中有一些拼写错误的单词。我的工作是识别哪些单词拼写错误,然后在我打印地址时在拼写错误的单词下面打印出星号或其他内容。我的问题在 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
}

附言。我知道它还不完整,还有很多 Unresolved 问题,它仍在进行中。

编辑:

我尝试根据我对 binarySearch 工作方式的理解制作一个新的搜索功能。这是该功能的代码。 “字符串 w” 将是要针对地址中的 testWord 进行测试的字典单词:

public static int binarySearch(String 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;
}

最佳答案

这就是你所需要的:

if(index < 0) {
System.out.println(testWord + " not in dictionary");
}

此外,通过检查 index 的绝对值,您可以轻松地在字典中找到与您输入错误的单词按字母顺序排列接近的单词。

关于Java - 二进制搜索()。如何为拼写检查设置 binarySearch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14864645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com