2012-12-12 45 views
0

我在尝试修复ArrayIndexOutOfBoundsException时遇到了最困难的时间。测验程序中的数组索引超出范围例外

我有一个逐行读取文件的方法。如果行上的名称和id匹配我传递给该方法的某些变量,则将该行保存到数组中。

该程序模拟测验。用户不能使用相同的名称和id超过2次;因此,该文件只包含具有相同名称和ID的两行。

我创建了一个名为temp的数组来保存文件中的这两行。如果文件为空,则用户进行两次尝试,并且当他再次尝试时,他被拒绝。所以如果你输入一个不同的名字和id,你应该再试2次。此时文件有两行来自前一个用户,但是当新用户尝试时,他只能进行一次测试。当他第二次尝试时,我得到数组越界异常。

我的问题是:数组temp是否保存了以前的值,这就是为什么我得到异常?

private String readFile(String id, String name) { 
    String[] temp = new String[3]; 
    int i = 1; 
    int index = 0; 
    String[] split = null; 
    String idCheck = null; 
    String nameCheck = null; 
    temp = null; 

    try { 
     BufferedReader read = new BufferedReader(new FileReader("studentInfo.txt")); 
     String line = null;   

     try { 
      while ((line = read.readLine()) != null) { 
       try { 
        split = line.split("\t\t"); 
       } catch (Exception ex) { 
       } 

       nameCheck = split[0]; 
       idCheck = split[1]; 

       if (idCheck.equals(id) && nameCheck.equals(name)) { 
        temp[index] = line; 
       } 

       index++; 
      } 
      read.close(); 
     } catch (IOException ex) { 
     } 
    } catch (FileNotFoundException ex) { 
    } 

    if (temp != null) { 
     if (temp[1] == null) { 
      return temp[0]; 
     } 
     if (temp[1] != null && temp[2] == null) { 
      return temp[1]; 
     } 
     if (temp[2] != null) { 
      return temp[2]; 
     } 
    } 

    return null; 
} 
+2

需要显示精确的异常和行号的堆栈跟踪。 – jn1kk

+2

你会在这里得到一个IOOB异常 - 'idCheck = split [1];' - 如果行上没有双标签。 – Jivings

+0

'temp [index] = line;' - >这似乎有问题。如果你的文件有超过3行符合你上面的'if'语句,你最终会得到'ArrayOutOfBoundsException'。 – Laf

回答

0

这是可能发生的情况

String[] split = "xxx\tyyyy".split("\t\t"); 
    System.out.println(split[0]); 
    System.out.println(split[1]); 

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 
    at Test.main(Test.java:17) 
1

我看到两个地方,你可以得到一个索引越界异常。首先是这样的代码:

try { 
    split = line.split("\t\t"); 
} catch (Exception ex) { 
} 
nameCheck = split[0]; 
idCheck = split[1]; 

如果该行不具有"\t\t"序列,然后split将只有一个元素,并试图访问split[1]会抛出异常。 (顺便说一下,你不应该默默地忽略异常!)

第二个(也是更可能的问题来源)是,你为每一行匹配id和name的行增加index,所以一旦你读了第三个此类行,index作为temp的下标出界。

您可以包括index < temp.lengthwhile循环条件,或者您可以使用ArrayList<String>temp,而不是String[]。这样你可以添加无限数量的字符串。

0

设置temp = null;

下一个参考温度后为:

if (idCheck.equals(id) && nameCheck.equals(name)) { 

    temp[index] = line; 
} 

我相信你应该删除线temp = null;。它所做的就是垃圾你刚刚在该行上面实例化的数组。

这指数让我触摸紧张,但我想,如果你确信正在读取的文件将永远不会有超过3行...