I am writing a program which detect misspelled words with Array in Java

lalala picture lalala · Oct 31, 2013 · Viewed 7.5k times · Source

I was writing a program which implement a spelling checker that reads from a standard dictionary file by using Array. This is my first time using Array and I don't really know how to recall methods. So, I think I made a mistake at Boolean method because the Eclipse kept giving me either one answer for both correct and incorrect words. Would anyone help me fixing my code?

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;
}

}

Answer

radimpe picture radimpe · Oct 31, 2013

You'll only get the 'correctSpelling' if that is the last word in the dictionary. Exit the loop when you find it.

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;
}