Java数组索引超出范围

时间:2014-03-13 23:38:03

标签: java

我有以下代码通过一行学生阅读,程序应该在每个空格分开,然后转到文本的下一部分,但我得到arrayindexoutofBound异常。 文本文件有几行,如下所示:

130002 Bob    B2123   35   34   B2132   34   54   B2143   23   34



public static void main(String[] args) throws FileNotFoundException {
    File f = new File("C:\\Users\\Softey\\Documents\\scores.txt");
    Scanner sc = new Scanner(f);

    List<MarkProcessing> people = new ArrayList<MarkProcessing>();

    while(sc.hasNextLine()){
        String line = sc.nextLine();
        String[] details = line.split("\\s+");

        String regNumber = details[0];
        String name = details[1];
        String modOne= details[2];
        int courseM = Integer.parseInt(details[3]);
        int examM = Integer.parseInt(details[4]);
        String modTwo = details[5];
        int courseM2 = Integer.parseInt(details[6]);
        int examM2 = Integer.parseInt(details[7]);
        String modThree = details[8];
        int courseM3 = Integer.parseInt(details[9]);
        int examM3= Integer.parseInt(details[10]);

        MarkProcessing p = new MarkProcessing(regNumber, name, modOne,courseM, examM, modTwo,courseM2,examM2, modThree, courseM3,  examM3);
        people.add(p);
    }


}

}

当进入细节[1]时,我得到索引错误。

3 个答案:

答案 0 :(得分:1)

如果没有关于输入文件的信息,我猜这是因为你的文件中有空行。如果是这种情况,你应该尝试一些东西以确保你有足够的碎片。为此,你的while循环可能是这样的。

while(sc.hasNextLine()){
    String line = sc.nextLine();
    String[] details = line.split("\\s+");
    if(details.length < 11) continue; // skip this iteration
    ...
}

请记住,如果您每行至少检查11件物品,这只会起作用。如果您需要更高级的解析输入方法,而他们可能有任意数量的课程。除了直接从索引存储值之外,你最好考虑另一种方法。

答案 1 :(得分:0)

你应该在解析之前尝试打印这条线,这样你就可以看到导致它爆炸的原因。

    String line = sc.nextLine();
    String[] details = line.split("\\s+");

    String regNumber = details[0];
    String name = details[1];
    String modOne= details[2];

你正在分裂空间。如果您遇到没有空格的行,那么只会有一个元素,因此details[1]会抛出IndexOutOfBoundsException

我的建议是仔细检查你的输入。是否有拖尾换行?如果是这样,那可能会被解释为空行

130002 Bob    B2123   35   34   B2132   34   54   B2143   23   34
<blank line>

答案 2 :(得分:-1)

要按空格分割,您需要使用:

String[] details = line.split(" "); // "\\s+" -> does not split by space.

在你的情况下,它试图通过正则表达式模式分割线条&#39; // s +&#39;由于未找到,因此将整行视为一个字符串。在这种情况下,字符串数组的大小为1.没有详细信息[1],因此您会收到此错误。

相关问题