简体   繁体   中英

How can i fix array index out of bound of my java code?

Hey guys can anyone help me in my problem about array index out of bound in my java code. Below is my full code having a problem.

public static double calculateMedian(double[] arr) {
    double[] sortedArr = sortarr(arr);

    double median;

    if (arr.length % 2 == 0) {
        int indexA = (arr.length-1) / 2;
        int indexB = (arr.length) / 2;

        median = ((double) (sortedArr[indexA] + sortedArr[indexB])) / 2; // this code has a error in index out of bounds.
    }   
    else {
        int index = (sortedArr.length - 1) / 2;
        median = sortedArr[ index ];
    }
    return median;  
}

This is my sorting fucntion

 public static double[] sortarr(double[] arr) {
    boolean performedSwap = true;
    double modeValue;

    while(performedSwap) {
        performedSwap = false;

        for (int i=0; i < arr.length-1; i++) {
            if (arr[i] > arr[i+1]) {
            modeValue = arr[i];
            arr[i] = arr[i+1];
            arr[i+1] = modeValue;

            performedSwap = true;
            }
        }
    }
    return arr;
}

如果arr.length = 0 (空数组),您的代码尝试采用sortedArr[0]并且您有此异常。

You are clearly passing an empty array.

Add an extra condition before checking for arr.length % 2 == 0 to see if arr.length == 0 .

Not sure what you would want to return as the median in that case.

The only case where the error can happen is if your array is empty. The median for empty array is none since there is no value to begin with.

public static double calculateMedian(double[] arr) {
    double[] sortedArr = sortarr(arr);

    double median;

    if (arr.length == 0) {
        return ; // return nothing if it is an empty array
    } else if (arr.length % 2 == 0) {
        int indexA = (arr.length-1) / 2;
        int indexB = (arr.length) / 2;

        median = ((double) (sortedArr[indexA] + sortedArr[indexB])) / 2; // this code has a error in index out of bounds.
    } else {
        int index = (sortedArr.length - 1) / 2;
        median = sortedArr[ index ];
    }
    return median;  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM