测验程序中的数组索引超出范围异常

时间:2012-12-12 19:30:18

标签: java arrays indexoutofboundsexception

我正在努力修复ArrayIndexOutOfBoundsException

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

该程序模拟测验。用户不能使用相同的名称和id超过2次;因此,该文件只包含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;
}

3 个答案:

答案 0 :(得分:1)

我看到两个地方可以获得索引超出范围的异常。首先是这段代码:

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

如果该行没有"\t\t"序列,那么split将只有一个元素,并且尝试访问split[1]将引发异常。 (顺便说一句:你不应该默默地忽略异常!)

第二个(更可能的问题来源)是你为每个具有匹配id和名称的行递增index,所以一旦你读到第三行这样的行,index就出来了作为temp的下标的边界。

您可以在index < temp.length循环条件中加入while,也可以使用ArrayList<String>代替temp而不是String[]。这样你可以添加无限数量的字符串。

答案 1 :(得分: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)

答案 2 :(得分:0)

设置temp = null;

对temp的下一个引用是:

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

    temp[index] = line;
}

我相信你应该删除第temp = null;行。它所做的就是将您刚刚在该行上方实例化的数组废弃。

该索引让我感到紧张,但我想如果您确定正在阅读的文件永远不会超过3行......