我在尝试修复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;
}
需要显示精确的异常和行号的堆栈跟踪。 – jn1kk
你会在这里得到一个IOOB异常 - 'idCheck = split [1];' - 如果行上没有双标签。 – Jivings
'temp [index] = line;' - >这似乎有问题。如果你的文件有超过3行符合你上面的'if'语句,你最终会得到'ArrayOutOfBoundsException'。 – Laf