2015-06-18 73 views
-2

這是我得到的錯誤,我不知道爲什麼。Java錯誤:java.lang.IndexOutOfBoundsException:索引:1,大小:1

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

我認爲這是數組列表,但是當我嘗試counter + 1時它也沒有工作。

+0

'list of size'小於被訪問的索引,假設'size是1,索引應該只有0不是1' –

+0

你調試過嗎? – DiSol

+2

你能否提供堆棧跟蹤與例外?你在哪個函數中得到這個異常? –

回答

0

隨着部分代碼的提供,您看起來只有diceData ArrayList中有一個元素。您需要在ArrayList中擁有與NUMBER_OF_SIDES一樣多的元素,以便您的循環在不拋出異常的情況下工作。

您可以通過打印diceData.size()來查看它是否等於或大於NUMBER_OF_SIDES。

0

你的下面的代碼將導致problem--

for (int col= 0; col < NUMBER_OF_SIDES; col++) 
    { 
     int counter = 0; 
     //Add each of the 6 letters to the die ArrayList representing 
     //the die letters by calling method addLetter in class Die 
     die.addLetter(diceData.get(counter).toString()); 
     counter++; 
    } 

這背後的原因是,

diceData ArrayList的參考實例只,但它並沒有包含在它的任何值。即diceData數組列表爲空。

所以,爲了避免這種情況做following--

for (int col= 0; col < NUMBER_OF_SIDES; col++) 
    { 
     int counter = 0; 
     //Add each of the 6 letters to the die ArrayList representing 
     //the die letters by calling method addLetter in class Die 
     if(!diceData.isEmpty()) 
     { 
     die.addLetter(diceData.get(counter).toString()); 
     counter++; 
     } 
     } 

而且我仍然無法理解爲什麼你總是初始化和上面福爾循環遞增計數器。?因爲我在代碼中沒有看到任何用法。

+0

根據他的代碼,它被初始化爲在構造函數中傳入的值 –

+0

diceData不爲空。該異常顯示大小爲1,並初始化爲作爲參數傳入的arrayList。 –

+0

這不能解決它。 – codegeek123

相關問題