[英]Array Index Out Of Bounds Exception how to handle it in the following program?
[英]Array index out of bounds exception in quiz program
我在尝试修复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;
}
我看到两个地方可以获取索引超出范围的异常。 首先是这段代码:
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
的下标范围。
您可以在while
循环条件中包括index < temp.length
,也可以将ArrayList<String>
用作temp
而不是String[]
。 这样,您可以添加无限数量的字符串。
这可能正在发生
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)
设置temp = null;
对temp的下一个引用是:
if (idCheck.equals(id) && nameCheck.equals(name)) {
temp[index] = line;
}
我相信您应该删除行temp = null;
。 它所做的只是将刚实例化的该行上方的数组丢弃。
该索引使我有些紧张,但是我想如果您确定正在读取的文件永远不会超过3行...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.