2014-03-13 86 views
0

我有以下代码读取一行学生,程序应该在每个空白处拆分,然后转到文本的下一部分,但是我得到了arrayindexoutofBound异常。 文本文件有几行是这样的:Java数组索引超出范围

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]我得到的指数错误。

+0

哪一行导致异常? – Scorpion

+3

让它检查拆分数组的大小,如果它小于11,则打印混乱的线条。 – CBredlow

+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

要通过空间分割,你需要使用:

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

在你的情况下,试图通过正则表达式模式“// S +”,由于该分割线是找不到的,它认为整行是一个字符串。在这种情况下,字符串数组的大小是1.没有细节[1],因此你会得到这个错误。

+3

\\ s +分割任意数量的空格。这不是原因。 – Tristan

+0

在这里查看'\\ s +'正则表达式:http://fiddle.re/5pk8j =>它匹配任意数量的空格... – donfuxx

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>