Java 为什么我的程序无限循环?
我的拼写检查程序没有给出任何错误代码,只是一遍又一遍地、无限次地对相同的单词进行拼写检查。 有没有办法停止这个无限循环,并对它检查的单词数量设置上限,例如,当十个不正确的单词被纠正时结束代码 我几乎可以肯定无限循环是这种方法的结果:Java 为什么我的程序无限循环?,java,loops,infinite-loop,Java,Loops,Infinite Loop,我的拼写检查程序没有给出任何错误代码,只是一遍又一遍地、无限次地对相同的单词进行拼写检查。 有没有办法停止这个无限循环,并对它检查的单词数量设置上限,例如,当十个不正确的单词被纠正时结束代码 我几乎可以肯定无限循环是这种方法的结果: public static void SpellChecker() throws IOException { dictionary = new Hashtable<String, String>(); System.ou
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);
}
}
public static void SpellChecker()引发IOException{
dictionary=新哈希表();
System.out.println(“搜索拼写错误…”);
试一试{
//阅读并储存字典中的单词
BufferedReader dictReader=新的BufferedReader(新文件阅读器(“dictionary.txt”);
while(dictReader.ready()){
字符串dictInput=dictReader.readLine();
String[]dict=dictInput.split(\\s”);//创建
//词典词汇
for(int i=0;i
您从不询问用户是否希望退出while循环内部。因此,user\u text
是用cleanString
初始化的,在循环中从不改变,因此是无限循环。cleanString的值是什么?放一些系统日志并调试值。.user\u text应该是用户输入的,对吗?但您从未要求用户输入任何内容。此外,永远不要使用ready()。它不会做你认为它会做的事。此外,布尔AND运算符是&&
,而不是&
。您的示例必须是最小且完整的。发布到GitHub的链接并不是最简单的。手动生成一些新代码,这些代码是完整的、可编译的,但也演示了行为。不要忘记,您也需要包含输入。当然,但是由于您在用户_文本不是“q”时进入循环,并且由于您从未在循环中请求新值,因此它将永远循环(除非cleanString等于“q”)。因此,无限循环。