如何在Java中越界修复数组索引?

时间:2018-12-03 02:38:39

标签: java

我在下面的Java代码中遇到问题,它返回超出范围的数组索引。谁能帮助我解决这个问题。

public static double calculateMedian(int[] arr) {

    int[] sortedArr = bubbleSort(arr); //this code returns ArrayIndexOutOfBoundsException 
}

public static int[] bubbleSort(int[] arr) {
    boolean performedSwap = true;
    int tempValue = 0;

    while(performedSwap) {
        performedSwap = false;

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

            performedSwap = true;
            }
        }
    }
    return arr;
}

java代码上方的输出:

C:\Users\root\Java>java Median_Methods
How many numbers will you input?
2
Input the 1st number:
1
Input the 2nd number:
4
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at Median_Methods.calculateMedian(Median_Methods.java:58)

1 个答案:

答案 0 :(得分:0)

arr.Length的值过多或为空。因此,为了不踩空值,您应该在循环内-1 arr.Length

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

            performedSwap = true;
            }
        }