![](/img/trans.png)
[英]Don't understand why I am getting index out of bounds exception when filling this 2d array
[英]why is the Arrayindex out of bound in the following code in java? I have checked the bounds but don't understand why/
Arrayindex out of bounds
錯誤,我尤其不知道為什么會發生。 我正在嘗試創建2N個元組對象,並嘗試將它們放入大小為2N的數組中
Tuple[] minuteunit = new Tuple[2*N];
if(!intervals.isEmpty())
{
for(i = 0; i < ((2*N)-1); i = 1+2)
{
minuteunit[i] = new Tuple(intervals.get(i).getBeginMinuteUnit(),"s");
minuteunit[i+1] = new Tuple(intervals.get(i).getEndMinuteUnit(),"e");
}
您很有可能在intervals.get(i)
中使用i
,因為i
遞增+2
。 我可以想象您在intervals
有N
值,因此當i >= (N/2)
您會溢出。
嘗試這個:
for(i = 0; i < N; i++)
{
minuteunit[2*i] = new Tuple(intervals.get(i).getBeginMinuteUnit(),"s");
minuteunit[2*i+1] = new Tuple(intervals.get(i).getEndMinuteUnit(),"e");
}
另外,假設間隔應包含N
個條目,則可以將intervals.isEmpty()
檢查更新為:
if(intevals.size() == N)
{
...
for(i = 0; i < ((2*N)-1); i = 1+2)
在每次迭代中,我等於3,所以它永遠不會完成。 我認為您想在每次迭代中添加2,因此請使用:
for(i = 0; i < ((2*N)-1); i = i+2)
您需要使循環的終止條件i<2*N-2
,否則,當i
為2*N-2
(最終將是),加2的迭代將i
推到數組末尾。
順便說一句,我假設您對i=1+2
迭代是一個錯字,而您實際上已經對i=i+2
編碼
我將在這里進行黑暗拍攝,並猜測也許intervals.get(i)
實際上是在這里引起您的問題的原因,而不是數組本身。 忽略似乎是錯字的增量,循環的條件似乎很好,因為如果i < 2*N - 1
,則i + 1 < 2*N
,因此數組沒有超出范圍的索引。 剩下intervals.get(i)
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.