2017-05-24 114 views
-2

我知道有幾個關於這個特定錯誤的帖子,但是這些帖子的答案都沒有解決我的問題。基本上我正在讀取一個txt文件到列表列表中。它編譯沒有錯誤,但是當我運行它時,我得到「ArrayIndexOutOfBoundsException:2」。顯然這個問題在第359行是「double tempArea = Double.parseDouble(tokenize [2]);」。我無法看到該行的任何錯誤,所以我也檢查了額外的大括號或分號,但沒有找到。我在下面列出了我的代碼。任何人都可以看到錯誤的原因可能是什麼?數組索引越界

ArrayList<String>listS = new ArrayList<>(); 


    try 
    { 
     BufferedReader bR = new BufferedReader (new FileReader("EssentialsSaleFile.txt")); 
     String fileRead = bR.readLine(); 
     while(fileRead != null) 
     { 
       String[] tokenize = fileRead.split(","); 
       String tempType = tokenize[0]; 
       String tempAddress = tokenize[1]; 
       double tempArea = Double.parseDouble(tokenize[2]); 
       int tempNumOfBedrooms = Integer.parseInt(tokenize[3]); 
       int tempNumOfToilets = Integer.parseInt(tokenize[4]); 
       int tempNumOfGarages = Integer.parseInt(tokenize[5]); 
       String tempSellerName = tokenize[6]; 
       String tempSellerPhone = tokenize[7]; 
       String tempSaleOfferDate = tokenize[8]; 
       String tempSaleOfferEndDate = tokenize[9]; 
       double tempAskingAmount = Double.parseDouble(tokenize[10]); 
       String tempAssignedEmployee = tokenize[11]; 
       double tempSalesCommissionPerc = Double.parseDouble(tokenize[12]); 

       String tempObj = new String(); 

       listS.add(tempObj); 
       fileRead = bR.readLine(); 


     } 



       bR.close(); 

    } 





     catch(FileNotFoundException ex) 
     { 
       JOptionPane.showMessageDialog(null,"File not here."); 
     } 
     catch (IOException e) 
     { 
     } 
+0

嗯,你的文本文件中只有兩個元素的行?提示:嘗試在分割之前記錄你分割的行...... –

+0

*顯然*'tokenize'只包含2個元素。這就是錯誤信息告訴你的,這是你必須研究的,在行前設置一個斷點並檢查'tokenize'和'fileRead'。 – luk2302

回答

1

問題不在於代碼本身。 tokensize數組包含與您行中逗號分隔字符串一樣多的元素。

由於訪問第三個元素(tokenize[2])時出現ArrayIndexOutOfBoundsException,因此文件中只有一個逗號。

例如: 該行foo,bar爲您提供了只有兩個元素的數組["foo","bar"]。訪問tokenize[2]將導致ArrayIndexOutOfBoundsException

0

答案很簡單。文件中有一行只包含一個逗號。用逗號分隔這一行返回一個只有兩個元素的數組,這使得訪問tokenize [2]越界。

首先,你應該檢查被檢查的行包含什麼。 之後,如果標記大小的長度爲13,則在分割後添加一個檢查,如果不是,則跳過該行或其他適當的操作,如顯示消息或記錄行。