我正在编写一个程序,该程序实现一个拼写检查器,该检查器使用 Array 从标准字典文件中读取。这是我第一次使用数组,我真的不知道如何记忆方法。所以,我认为我在 boolean 方法上犯了一个错误,因为 Eclipse 不断地为我提供正确和错误单词的一个答案。有人能帮我修复我的代码吗?
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
public class CheckingWords {
public static void main(String[] args) throws FileNotFoundException
{
Scanner input = new Scanner(System.in);
System.out.println("Enter the word you would like to spell check");
String userWord = input.nextLine();
final String filename = "americanWords.txt";
String[] words = dictionary(filename);
boolean correctSpelling = checkWord(words, userWord);
if (correctSpelling)
{
System.out.println("That word is not correct");
}
else
{
System.out.println("That is the correct spelling");
}
}
public static String[] dictionary(String filename) throws FileNotFoundException
{
final String fileName = "americanWords.txt";
Scanner dictionary = new Scanner(new File(fileName));
int dictionaryLength =0;
while (dictionary.hasNext())
{
++dictionaryLength;
dictionary.nextLine();
}
String [] words = new String[dictionaryLength];
for ( int i = 0; i < words.length ; i++)
dictionary.close();
return words;
}
public static boolean checkWord(String[] dictionary, String userWord)
{
boolean correctSpelling = false;
for ( int i =0; i < dictionary.length; i++)
{
if (userWord.equals(dictionary[i]))
{
correctSpelling = true;
}
else
correctSpelling = false;
}
return correctSpelling;
}
}
最佳答案
只有当这是字典中的最后一个单词时,您才会得到“正确的拼写”。找到后退出循环。
public static boolean checkWord(String[] dictionary, String userWord)
{
for ( int i =0; i < dictionary.length; i++)
{
if (userWord.equals(dictionary[i]))
{
return true;
}
}
return false;
}
关于java - 我正在编写一个程序,用 Java 中的数组检测拼写错误的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19704925/