我的拼写检查程序没有给出任何错误代码,只是无限地拼写检查相同的单词。 有没有办法阻止这个无限循环,并对它检查的单词数量设置上限,例如,在修正了10个不正确的单词时结束代码?
我几乎可以肯定无限循环是这种方法的结果:
public static void SpellChecker() throws IOException {
dictionary = new Hashtable<String, String>();
System.out.println("Searching for spelling errors ... ");
try {
// Read and store the words of the dictionary
BufferedReader dictReader = new BufferedReader(new FileReader("dictionary.txt"));
while (dictReader.ready()) {
String dictInput = dictReader.readLine();
String[] dict = dictInput.split("\\s"); // create an array of
// dictionary words
for (int i = 0; i < dict.length; i++) {
// key and value are identical
dictionary.put(dict[i], dict[i]);
}
}
dictReader.close();
String user_text = "";
// Initializing a spelling suggestion object based on probability
SuggestSpelling suggest = new SuggestSpelling("wordprobabilityDatabase.txt");
// get user input for correction
while (!user_text.equalsIgnoreCase("q")) {
// CleanString is a string full of words to be spell checked
user_text = cleanString;
String[] words = user_text.split(" ");
int error = 0;
for (String word : words) {
suggestWord = true;
String outputWord = checkWord(word);
if (suggestWord) {
System.out.println("Suggestions for " + word +
" are: " + suggest.correct(outputWord) + "\n");
error++;
}
}
if (error == 0 & !user_text.equalsIgnoreCase("q")) {
System.out.println("No mistakes found");
}
}
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
答案 0 :(得分:0)
你永远不会在while循环内询问用户是否要退出。所以user_text
初始化为cleanString
,并且永远不会在循环内部发生变化,因此无限循环。