我有这种方法来获得中值,
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 例外。 有人可以帮我解决错误吗?
答案 0 :(得分:3)
您应该使用i < numberList.length
,而不是i <= numberList.length;
数组的合法索引为[0, array.length-1]
,即array.length
不是合法索引
答案 1 :(得分:2)
简化回答
如果您只想the median value,只需在numberList
上使用if-else,就不需要任何子数组:
public double getMedian(double[] numberList) {
int middle = numberList.length / 2;
if (numberList.length % 2 == 0) {
double total = numberList[middle - 1] + numberList[middle]
return total / 2;
} else {
return numberList[middle];
}
}
原始答案
正如我在Zim-Zam的回答中所说,这个循环也没有使用正确的索引:
for (int i = numberList.length; i >= last.length; i--) {
last[i] = numberList[i];
}
last
只能0
到numberList.length / 2
(向下舍入)
看起来您希望将numberList
分为first
和last
,只需使用:
int[] first = Arrays.copyOfRange(numberList, 0, factor);
int[] last = Arrays.copyOfRange(numberList, factor, numberList.length);
而不是你的for循环。