检查单词是否在文本文件中

时间:2014-03-31 00:01:20

标签: java

所以,我有一个程序应该通过一个名为dictionary.txt的文件,并检查输入的单词是否在字典文本文件中。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Main {


public static void main(String[] args){

    String word = null;
    Scanner scan = new Scanner(System.in);
    word = scan.nextLine();

    try {
        if(isInDictionary(word, new Scanner(new File("dictionary.txt")))){
            System.out.println(word + " is in the dictionary");
        } else System.out.println(word + " is NOT in the dictionary");
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public static boolean isInDictionary(String word, Scanner dictionary){

    List<String> dictionaryList = new ArrayList<String>();
    for(int i = 0; dictionary.hasNextLine() != false; i++){
        ++i;
        dictionaryList.add(dictionary.nextLine());
        if(dictionaryList.get(i) == word){
            return true;
        }
    }

    return false;

}

}

当我尝试运行它时,我收到此错误:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at io.github.mediocrelogic.checkDictionary.Main.isInDictionary(Main.java:34)
at io.github.mediocrelogic.checkDictionary.Main.main(Main.java:19)

为什么我在这里收到IndexOutOfBoundsException?代码没有语法错误。 dictionary.txt文件大约是19.95mb,这就是为什么我收到这个例外?

3 个答案:

答案 0 :(得分:4)

如果您在循环中移除了迷路++i,则应解决您的问题。

for(int i = 0; dictionary.hasNextLine() != false; i++){
    //++i;  // <-- THIS SHOULD GO AWAY!
    dictionaryList.add(dictionary.nextLine());
    if(dictionaryList.get(i) == word){
        return true;
    }
}

您已在i语句中递增for。通过在循环内再次递增它,i越过字典的末尾,因此异常。

顺便说一句,另请参阅How do I compare strings in Java?,因为您不希望使用==来比较字符串。

答案 1 :(得分:4)

请完整删除代码行++i;i已在for循环中递增{/ 1}。

答案 2 :(得分:2)

for(int i = 0; dictionary.hasNextLine() != false; i++){
    ++i;

在该代码之后,你的计数器增加了两次,但是在此

之后,ArrayList的索引只增加了一个
dictionaryList.add(dictionary.nextLine());

这意味着你总是试图从ArrayList中获取一个项目,其中i等于ArrayList Index + 1

你应该从你的代码中删除这个++ i,它会起作用

此外,您可以使用Regex和matcher对象

更好地搜索单词到txt文件

http://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html

或Indexof更快速搜索

http://www.homeandlearn.co.uk/java/indexOf.html