2013-02-10 84 views
-1

我工作的一個列表陣列功課在Java中 ,但我一直在得到value()方法得到這個ArrayIndexOutOfBoundsException錯誤ArrayIndexOutOfBoundsException異常錯誤的Java

public int getValue() throws DSException { 
     //returns the value of current position 
     //throw exception when there are no elements in the list 
     if (listArray.length == 0){ 
      throw new DSException(); 
     } 
     return listArray[curr]; 
} 
+4

那麼...什麼是'curr'? – Makoto 2013-02-10 19:21:30

+1

問題是'curr'大於或等於'listArray.length'。下一次使用調試器來看看這個。 – 2013-02-10 19:22:17

+0

curr =當列表大小爲0時,數組的當前位置和-1 – Envix 2013-02-10 19:36:39

回答

0

您需要檢查是否curr是有效的,如果不長是!= 0

它應該是這樣的:

public int getValue() throws DSException { 
     //returns the value of current position 
     //throw exception when there are no elements in the list or less than 'curr' 
     if (listArray.length <= curr){ 
       throw new DSException(); 
     } 
     return listArray[curr]; 
} 
1

檢查參數 「電流」,它與listArray.length比較

0

在那裏你可以得到這個錯誤的地方是:return listArray[curr]

試試這個

return listArray.length-1?listArray[curr]:"whatever you want" 
相關問題