我在尝试修复ArrayIndexOutOfBoundsException时遇到了最困难的时候。
我有一个逐行读取文件的方法。如果该行上的name和id与我传递给该方法的某些变量相匹配,那么我将该行保存到一个数组中。
这个程序模拟了一个测验。用户使用相同的名称和id不能超过2次;因此,该文件只包含2行具有相同的名称和id的代码。
我创建了一个名为temp的数组来保存文件中的这两行。如果文件为空,则用户进行两次尝试,当他再次尝试时,将被拒绝。因此,如果您输入一个不同的名称和id,您应该会再尝试两次。此时,该文件有两行来自前一个用户的内容,但是当新用户尝试测试时,他只能进行一次测试。当他第二次尝试时,我得到了数组越界异常。
我的问题是:数组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;
}发布于 2012-12-13 03:37:36
我发现有两个地方可以让索引越界异常。首先是这段代码:
try {
split = line.split("\t\t");
} catch (Exception ex) {
}
nameCheck = split[0];
idCheck = split[1];如果该行没有"\t\t"序列,那么split将只有一个元素,并且尝试访问split[1]将抛出异常。(顺便说一句:您不应该默默地忽略异常!)
第二个(也是更有可能的问题来源)是,对于每一行具有匹配的id和名称的行,都会递增index,因此,一旦读取了第三行这样的行,index就越界了,因为它是temp的下标。
您可以在while循环条件中包含index < temp.length,也可以使用ArrayList<String> for temp而不是String[]。这样,您可以添加无限数量的字符串。
发布于 2012-12-13 03:36:47
这就是可能发生的事情。
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)发布于 2012-12-13 03:43:32
设置temp = null;后
对temp的下一个引用是:
if (idCheck.equals(id) && nameCheck.equals(name)) {
temp[index] = line;
}我认为您应该删除行temp = null;。它所做的一切就是将您刚刚在该行上实例化的数组丢弃。
这个索引让我有点紧张,但我想如果你确定正在读取的文件永远不会超过3行……
https://stackoverflow.com/questions/13847163
复制相似问题