![](/img/trans.png)
[英]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.