MedianCalc()方法给我IndexOutOfBounds Exception

时间:2013-04-09 17:29:56

标签: java android indexoutofboundsexception

我有这种方法来获得中值,

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 例外。 有人可以帮我解决错误吗?

2 个答案:

答案 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只能0numberList.length / 2(向下舍入) 看起来您希望将numberList分为firstlast,只需使用:

int[] first = Arrays.copyOfRange(numberList, 0, factor);
int[] last = Arrays.copyOfRange(numberList, factor, numberList.length);

而不是你的for循环。