从文本文件中的单行存储数组中每个单词的单词

时间:2013-07-23 13:01:29

标签: java

我一直在研究一个项目,它会扫描每行的文本文件行,并且每行,行中的每个单词都将存储在一个数组中

这是我现在的代码。当从Answer.txt文件存储时,会发生错误。有人可以帮帮我吗?

try
    {
        String s = sc.nextLine();
        //System.out.println(s);
        String[] Question = s.split(" ");

        for(int i=0;i<=Question.length;i++)
        {
            System.out.println(Question[i]);
        }//debug

        s = sc2.nextLine();
        //System.out.println(s2);
        String[] Answer = s.split(" ");

        for(int c=0;c<=Answer.length;c++)
        {
            System.out.println(Answer[c]);
        }//debug
    }
    catch (ArrayIndexOutOfBoundsException e)
    {
        System.out.println("...");
    }

2 个答案:

答案 0 :(得分:3)

您可能会遇到ArrayIndexOutOfBounds例外情况。

for(int i=0;i<=Question.length;i++)

应该是:

for(int i=0;i<Question.length;i++)
             ^

(另一个循环也一样)。

<强>为什么

请记住,Java中的数组从零开始。因此,如果您有一个大小为N的数组,则索引将从0N - 1N的总和)。

答案 1 :(得分:1)

您可以使用“foreach”循环避免索引计数。

for (String s: Question){
    System.out.println(s);
}