从文本文件中读取单词到数组中

时间:2015-11-30 22:18:40

标签: java arrays dictionary file-io java.util.scanner

我试图制作一个拼写检查程序。我想将字典文件中的单词读入数组,然后将另一个文本文件中的单词与该字典数组进行比较,最后打印出任何拼写错误的单词。我面临的问题是我的扫描仪正在读取一个长字符串。如果您要运行该程序,您会看到它将变量word显示为文本文件的全部内容,并且它只运行一次二进制搜索比较(意味着字典数组只有一个元素) , 我认为)。以下是我的代码,请给我任何你可能有的建议。提前谢谢!

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class spellChecker {

    private String[] dictionaryArray; 

    public static void main(String[] args) throws Exception
    {
        spellChecker spellcheck = new spellChecker();
        spellcheck.textFileRead(spellcheck.dictionaryRead());
    } 

    public String[] dictionaryRead() throws Exception
    {
        Scanner s = new Scanner(new File("dictionary.txt")).useDelimiter("\\s+");
        ArrayList<String> list = new ArrayList<String>();
        while (s.hasNext())
        {
            list.add(s.next());
        }
        s.close();

        dictionaryArray = list.toArray(new String[0]);
        return dictionaryArray;
    }

    public void textFileRead(String [] dictionaryArray) throws Exception
    {
        // Find and read the file
        // Use scanner for input file
        Scanner inputFileScan = new Scanner(new File("test.txt")).useDelimiter("\\s+");

        //Check for next line in text file
        while (inputFileScan.hasNext())
        {
            String word = inputFileScan.next();
            System.out.println("word: " + word);
            binarySearch(word);
        }
        inputFileScan.close();
    }

    public void binarySearch(String word)
    {
        int first = 0;
        int last  = dictionaryArray.length;
        while (first < last) {
          int mid = first + ((last - first) / 2);
          if (word.compareTo(dictionaryArray[mid]) < 0) 
          {
              last = mid;
              System.out.println("reached compare < 0");
          } 
          else if (word.compareTo(dictionaryArray[mid]) > 0) 
          {
              first = mid + 1;
              System.out.println("reached compare > 0");
          } 
          else if (word.compareTo(dictionaryArray[mid]) == 0)
          {
              System.out.println("reached compare = 0");
              break;
          }         
        }  
        if(first >= last)
            System.out.println("reached error word: " + word);
    }
} 


}

0 个答案:

没有答案