gpt4 book ai didi

java - MedianCalc() 方法给我 IndexOutOfBounds 异常

转载 作者:行者123 更新时间:2023-12-01 17:24:45 25 4
gpt4 key购买 nike

我有这个方法来获取中值,

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com