【发布时间】:2020-08-08 10:48:45
【问题描述】:
我正在编写一个简单的拼写检查器。只是为了检查用户文本的拼写与一个小字典文件的拼写并进行比较。
“dictionary.txt”文件包含:
my
name
is
这是我检查用户文本并将其与字典进行比较的代码:
import java.util.Scanner;
import java.io.File;
public class SpellChecker
{
public static void main(String[] args) throws Exception
{
Scanner write = new Scanner(System.in);
System.out.println("Type a sentence and I will check your spelling/correct words :)");
String sentence = write.nextLine();
String[] splitSentence = sentence.split(" ");
for(int i = 0; i < splitSentence.length; i++)
{
Scanner read = new Scanner(new File("dictionary.txt"));
while(read.hasNextLine())
{
String compare = read.nextLine();
if(compare.equalsIgnoreCase(splitSentence[i]))
{
System.out.println(splitSentence[i] + " : correct");
}
else
{
System.out.println(splitSentence[i] + " : incorrect");
}
}
}
}
}
这是我得到的输出。
Type a sentence and I will check your spelling/correct words :)
Heyo my name is Ivam
Heyo : incorrect
Heyo : incorrect
Heyo : incorrect
my : correct
my : incorrect
my : incorrect
name : incorrect
name : correct
name : incorrect
is : incorrect
is : incorrect
is : correct
Ivam : incorrect
Ivam : incorrect
Ivam : incorrect
以下是我预期的输出:
Type a sentence and I will check your spelling/correct words :)
Heyo my name is Ivam
Heyo : incorrect
my : correct
name : correct
is : correct
Ivam : incorrect
【问题讨论】:
-
你的字典文件是不是每行只有一个单词?
-
是的。它有 3 行 'my'、'name' 和 'is'
-
这是因为您的
while循环逻辑。您实际上是在使用单词检查每一行并将其打印为correct/incorrect以进行每行检查。 -
您的字典可能有“空格”或不可打印的控制字符,例如回车或换行。您应该从行中解析出字符串。