2012-12-12 46 views
0

我在嘗試修復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; 
} 
+2

需要顯示精確的異常和行號的堆棧跟蹤。 – jn1kk

+2

你會在這裏得到一個IOOB異常 - 'idCheck = split [1];' - 如果行上沒有雙標籤。 – Jivings

+0

'temp [index] = line;' - >這似乎有問題。如果你的文件有超過3行符合你上面的'if'語句,你最終會得到'ArrayOutOfBoundsException'。 – Laf

回答

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) 
1

我看到兩個地方,你可以得到一個索引越界異常。首先是這樣的代碼:

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的下標出界。

您可以包括index < temp.lengthwhile循環條件,或者您可以使用ArrayList<String>temp,而不是String[]。這樣你可以添加無限數量的字符串。

0

設置temp = null;

下一個參考溫度後爲:

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

    temp[index] = line; 
} 

我相信你應該刪除線temp = null;。它所做的就是垃圾你剛剛在該行上面實例化的數組。

這指數讓我觸摸緊張,但我想,如果你確信正在讀取的文件將永遠不會有超過3行...