java - 我正在编写一个程序,用 Java 中的数组检测拼写错误的单词

标签 java arrays misspelling

我正在编写一个程序,该程序实现一个拼写检查器,该检查器使用 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/

相关文章:

java - Android JSON API 调用

java - 使用jpos打包iso8583消息时得到错误的位图?

java - 将 log4j2 与 slf4j 一起使用 : java. lang.StackOverflowError

arrays - 在 O(n) 中找出具有最多 1 的行

c - 如何在循环中使用 scanf 来获取 c 中的 char* 数组

javascript - Post 方法抛出错误

java - 在 Eclipse 中拼错方法名称后如何恢复自动完成?

java - 有一个 Controller 类可以促进其他类之间的通信吗?

arrays - VBA:变体数组与类型数组与非键控集合的迭代速度

php - 如何从数据库中获取 "redefine search"或更正 "misspelling"