1

我正在编写一个程序,它实现了一个拼写检查器,它使用 Array 从标准字典文件中读取。这是我第一次使用 Array,我真的不知道如何调用方法。所以,我认为我在布尔方法上犯了一个错误,因为 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;
}

}
4

3 回答 3

1

如果这是字典中的最后一个单词,您只会得到“正确的拼写”。找到后退出循环。

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;
}
于 2013-10-31T11:16:32.430 回答
0
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;
}

或者

尝试

public static boolean checkWord(String[] dictionary, String userWord) {
  for(String str : dictionary) {
    if(str.equalsIgnoreCase(userWord))
      return true;
  }
  return false
}

true如果单词在字典中可用,这将返回

否则会返回false

于 2013-10-31T11:16:25.697 回答
-1

你的代码有什么问题,即使他已经找到了世界,它仍然在字典中搜索。尝试这个

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;
           break;
        }
    }
    return correctSpelling;
}
于 2013-10-31T11:17:50.517 回答