我在申请拼写检查时遇到问题。当拼写错误时,我正在尝试使用soundEx算法工作。我希望它为用户输入错误时的拼写提供建议
下面是我的拼写检查应用程序
public class SpellChecker2 {
public static void main(String[] args) throws FileNotFoundException
{
SoundEx2 phonetics = new SoundEx2();
Scanner input = new Scanner(System.in);
System.out.println("Please enter a String");
String userWord = input.nextLine();
System.out.println();
final String theDictionary = "dictionary.txt";
TreeSet<String> words = dictionary(theDictionary);
if(words.contains(userWord.toLowerCase()))
{
System.out.println("The spelling is correct");
} else {
System.out.println("Incorrect spelling of " + userWord);
}
}
public static TreeSet<String> dictionary(String filename) throws FileNotFoundException
{
final String fileName = "dictionary.txt";
TreeSet<String> theWords = new TreeSet<String>();
try (Scanner dictionary = new Scanner(new File(fileName))) {
while (dictionary.hasNextLine()) {
theWords.add(dictionary.nextLine());
}
}
return theWords;
}
}
这是我尝试实现的soundEx算法
public class SoundEx2 {
public String encode(String s) {
char[] ex = s.toUpperCase().toCharArray();
char numberOneLetter = ex[0];
//This is rule 2
for(int i = 0; i < ex.length; i++) {
switch(ex[i]) {
case 'A': {ex[i] = '0'; break;}
case 'B': {ex[i] = '1'; break;}
case 'C': {ex[i] = '2'; break;}
case 'D': {ex[i] = '3'; break;}
case 'E': {ex[i] = '0'; break;}
case 'F': {ex[i] = '1'; break;}
case 'G': {ex[i] = '2'; break;}
case 'H': {ex[i] = '0'; break;}
case 'I': {ex[i] = '0'; break;}
case 'J': {ex[i] = '2'; break;}
case 'K': {ex[i] = '2'; break;}
case 'L': {ex[i] = '4'; break;}
case 'M': {ex[i] = '5'; break;}
case 'N': {ex[i] = '5'; break;}
case 'O': {ex[i] = '0'; break;}
case 'P': {ex[i] = '1'; break;}
case 'Q': {ex[i] = '2'; break;}
case 'R': {ex[i] = '6'; break;}
case 'S': {ex[i] = '2'; break;}
case 'T': {ex[i] = '3'; break;}
case 'U': {ex[i] = '0'; break;}
case 'V': {ex[i] = '1'; break;}
case 'W': {ex[i] = '0'; break;}
case 'X': {ex[i] = '2'; break;}
case 'Y': {ex[i] = '0'; break;}
case 'Z': {ex[i] = '2'; break;}
}
}
//Applying the rules
//rule 1
String output = "" + numberOneLetter;
//rule 3
for(int i = 1; i < ex.length; i++) {
if(ex[i] != ex[i - 1] && ex[i] != '0') {
output += ex[i];
}
}
//rule 4
output = output + "0000";
return output.substring(0, 4);
}
}
有什么办法可以解决我的错误或找到使soundEx算法正常工作的方法。结果未正确显示。
我得到的结果是:
Please enter a String
catsss
Incorrect spelling of catsss
我正在寻找一种建议如何正确拼写猫的方法