【发布时间】:2016-12-31 15:29:59
【问题描述】:
我有整数计数,这是我的数组索引,假设计数等于 5,所以我的 arrayWeight[count] 索引/计数等于 5。
数组中的值是双精度的,数组中的所有 5 个单元格都被使用并包含值。
现在我愿意将所有arrayWeight[] 值添加到DataPoint[] 数组中,尽管DataPoint[] 中的索引等于6(计数+ 1)。
并且数组中的第六个索引在循环之外使用,如下所示:
double[] arrayWeight = new double[count]; // Array of user weight
DataPoint[] dp = new DataPoint[count+1];
for (int i = 0; i < count; i++) { // Array weight is inserted into datapoints y and i is the x so the graph will follow the (x,y)
dp[i] = new DataPoint(i, arrayWeight[i]);
Log.d("ArrayWeight", "equals: " + arrayWeight[i]);
Log.d("Array", "equals: " + i);
}
dp[count+1] = new DataPoint(count+1, db.getDetails().getWeight());
return dp;
我可以告诉你,当我从索引中删除 +1 并仅使用 count 时,代码正在运行,但我需要使用 count + 1 以便可以向 DataPoint[] 数组添加另一个值。
错误信息:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.none.myapplication, PID: 12760
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.none.myapplication/com.none.myapplication.MainActivity}:
java.lang.ArrayIndexOutOfBoundsException: length=6; index=6
如何正确创建array[index+1],才不会返回致命错误?
【问题讨论】:
-
你的数组去
0-5意思是6元素,所以你的数组中的最大位置是5而不是6 -
为什么你认为等于数组长度(或“大小”)的数字是有效索引?
-
@PavneetSingh 我在循环之后添加第六个元素。
-
您的数组
DataPoint[] dp = new DataPoint[count+1];的大小为count+1,因此其最大索引为count,但在dp[count+1] = new DataPoint(count+1, db.getDetails().getWeight());中,您尝试使用超出[0, count]范围的索引。 -
@Tom 那我该怎么写呢?