2013-10-19 85 views
3

我試圖讀取Java中的某個文件,並將其製作成多維數組。每當我從腳本讀取一行代碼,控制檯說:Java ArrayList IndexOutOfBoundsException索引:1,大小:1

Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1 

我知道這個錯誤是,當編碼無法達到的具體指標造成的,但我不知道如何在修復此時此刻。

這是我編碼的一個例子。

int x = 1; 
while (scanner.hasNextLine()) { 
    String line = scanner.nextLine(); 
    //Explode string line 
    String[] Guild = line.split("\\|"); 
    //Add that value to the guilds array 
    for (int i = 0; i < Guild.length; i++) { 
    ((ArrayList)guildsArray.get(x)).add(Guild[i]); 
    if(sender.getName().equals(Guild[1])) { 
     //The person is the owner of Guild[0] 
     ownerOfGuild = Guild[0]; 
    } 
    } 
    x++; 
} 

**文本文檔**

Test|baseman101|baseman101|0| 
Test2|Player2|Player2|0| 

其他解決方案,比如一個在這裏找到:Write to text file without overwriting in Java

在此先感謝。

+0

好,異常說發生了什麼異常時的水平。數組大小爲1,您訪問位置1.您的邏輯不正確! – diegoaguilar

+0

我以爲ArrayLists動態增加? – baseman101

+1

他們確實增加dinamically,但他們是0基於和訪問比實際更大的索引將導致異常 – diegoaguilar

回答

4

問題1 - >int x = 1;
解決方案:x應爲0

問題來開始2->

((ArrayList)guildsArray.get(x)).add(Guild[i]); 

您正在增加x如此if x >= guildsArray.size()那麼你將得到java.lang.IndexOutOfBoundsException

解決方案

if(x >= guildsArray.size()) 
     guildsArray.add(new ArrayList()); 
for (int i = 0; i < Guild.length; i++) { 
    ((ArrayList)guildsArray.get(x)).add(Guild[i]); 
    if(sender.getName().equals(Guild[1])) { 
     //The person is the owner of Guild[0] 
     ownerOfGuild = Guild[0]; 
    } 
    } 
+0

謝謝!這個伎倆。 – baseman101

+0

@ baseman101很高興聽到它..你的歡迎! – Prabhakaran

+0

這真的救了我的屁股。 –

0

的問題發生在這裏:

... guildsArray.get(x) ... 

但這裏引起的:

int x = 1; 
while (scanner.hasNextLine()) { 
    ... 

由於類別和陣列從零開始(第一個元素是索引0)。

試試這個:

int x = 0; 
相關問題