2014-03-31 54 views
1

因此,我有一个程序应该通过名为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,这就是为什么我收到此异常?

+0

“没有语法错误” 的JVM说,有。 – aliteralmind

+1

@aliteralmind Pedantic:编译器会捕获语法错误,而不是JVM。 :) –

+0

JVM根据代码中的错误报告了运行时错误。 OP是正确的,代码的语法不是这个问题的根本原因。 –

回答

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

你已经在你的for声明递增i。通过在循环内再次递增它,i越过字典的末尾,因此是例外。

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

+0

啊,那么字典列表会变大一倍呢?谢谢! – user3479380

+0

@ user3479380不,它没有。但是,索引的增长速度是词典的两倍,因此当您尝试访问字典中的索引时,您肯定会遇到超出界限的异常。我已经删除了这个陈述,因为它是为了解释,但它似乎误导了你。 –

+0

@ user3479380您可能希望阅读['ArrayList.get()']的文档(http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#get(int )),这清楚地解释了这种例外的含义。 –

4

请完整删除代码行++i;i已在for循环中增加。

+0

会做什么,忘了那些小细节,因为它最初是一个while循环。 – user3479380

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

之后代码的计数器增加两次,但在这之后

dictionaryList.add(dictionary.nextLine()); 

只是增加了一个ArrayList中这意味着你总是试图从ArrayList的项目随着我的指数等于到ArrayList的指数+ 1

您应该删除此++我从你的代码和它的将工作

你也可以得到更好的方法来搜索词成使用正则表达式txt文件,并匹配对象

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

或INDEXOF的伶俐搜索

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

相关问题