[英]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
error is showing up and I have particularly no idea why it is hapening. Arrayindex out of bounds
错误,我尤其不知道为什么会发生。 I am trying create 2N tuple objects and trying to put them in a array of size 2N 我正在尝试创建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");
}
it is most likely the face you are using i
in intervals.get(i)
, because i
is incrementing +2
. 您很有可能在intervals.get(i)
中使用i
,因为i
递增+2
。 I would imagine you have N
values in intervals
and therefore when i >= (N/2)
you get an overflow. 我可以想象您在intervals
有N
值,因此当i >= (N/2)
您会溢出。
Try this: 尝试这个:
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");
}
Also, assuming intervals should contain N
entries, you could update your intervals.isEmpty()
check to: 另外,假设间隔应包含N
个条目,则可以将intervals.isEmpty()
检查更新为:
if(intevals.size() == N)
{
...
for(i = 0; i < ((2*N)-1); i = 1+2)
At each iteration i equals 3, so it never finishes. 在每次迭代中,我等于3,所以它永远不会完成。 I think you want to add 2 at each iteration so use: 我认为您想在每次迭代中添加2,因此请使用:
for(i = 0; i < ((2*N)-1); i = i+2)
You need to make your loop's termination condition i<2*N-2
, otherwise the iteration of adding 2 will push i
over the end of your array when i
is 2*N-2
(which it wi eventually be). 您需要使循环的终止条件i<2*N-2
,否则,当i
为2*N-2
(最终将是),加2的迭代将i
推到数组末尾。
btw, I assume that your iteration of i=1+2
is a typo, and you have actually coded i=i+2
顺便说一句,我假设您对i=1+2
迭代是一个错字,而您实际上已经对i=i+2
编码
I'm going to take a shot in the dark here and guess that maybe intervals.get(i)
is what's actually causing your problem here and not the array itself. 我将在这里进行黑暗拍摄,并猜测也许intervals.get(i)
实际上是在这里引起您的问题的原因,而不是数组本身。 Ignoring what appears to be a typo in the increment, the condition for your loop seems to be fine, since if i < 2*N - 1
, then i + 1 < 2*N
and so there's no out of bound index for the array . 忽略似乎是错字的增量,循环的条件似乎很好,因为如果i < 2*N - 1
,则i + 1 < 2*N
,因此数组没有超出范围的索引。 That leaves the intervals.get(i)
method. 剩下intervals.get(i)
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.