-5

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

这是我现在的代码。当涉及从 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("...");
    }
4

2 回答 2

3

您可能会收到ArrayIndexOutOfBounds异常。

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

应该:

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

(另一个循环也一样)。

为什么

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

于 2013-07-23T13:02:44.973 回答
1

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

for (String s: Question){
    System.out.println(s);
}
于 2013-07-23T13:10:17.340 回答