我有这个方法来获取中值,
public double getMedian(double[] numberList) {
int factor = numberList.length;
double[] first = new double[(int) factor / 2];
double[] last = new double[first.length];
double[] middleNumbers = new double[1];
for (int i = 0; i < first.length; i++) {
first[i] = numberList[i];
}
for (int i = numberList.length; i >= last.length; i--) {
last[i] = numberList[i];
}
for (int i = 0; i <= numberList.length; i++) {
if (numberList[i] != first[i] || numberList[i] != last[i])
middleNumbers[i] = numberList[i];
}
if (numberList.length % 2 == 0) {
double total = middleNumbers[0] + middleNumbers[1];
return total / 2;
} else {
return middleNumbers[0];
}
}
但是给我一个IndexOutOfBounds异常。 有人可以帮我解决这个错误吗?
最佳答案
您应该使用i < numberList.length
,不是i <= numberList.length;
数组的合法索引是 [0, array.length-1]
,即array.length
不是合法索引
关于java - MedianCalc() 方法给我 IndexOutOfBounds 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15908574/