1

请考虑以下代码:

import java.io.*; //Sorts by dividing the array in 2 groups then joining them

public class Esercizio29 {static void  join(char[] a, int l, int m, int u) {
    char[] b = new char[u - 1 + 1];
    int i = l, j = m + 1, k = 0;

    while (i <= m && j <= u) 
        if (a[i] <= a[j])
            b[k++] = a[i++];
        else
            b[k++] = a[j++];
    while (i <= m)
        b[k++] = a[i++];
    while (j <= u)
        b[k++] = a[j++];        
    for (k = 0; k <= u - l; k++)
        a[k + l] = b[k];
}
//Sorts the array from l to u
static void sort(char[] a, int l, int u) {
    int m;
    if (l != u) {
        m = (l + u) / 2;
        sort(a,l,m);
        sort(a,m + 1,u);
        join(a,l,m,u);
    }
}



public static void main(String[] args) throws IOException{
    final int N = 16;
    char temp, v[] = new char[N];

    for (int i = 0; i <  N; i++)
        v[i] = (char) System.in.read();
    sort(v, 0, N - 1);
    System.out.println("Vettore ordinato: ");
    for(int i = 0; i < N; i++)
        System.out.print(v[i]);
    System.out.println();
}}

运行此代码后,它给了我这个结果:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

at Esercizio29.fondi(Esercizio29.java:14)

at Esercizio29.ordina(Esercizio29.java:27)

at Esercizio29.ordina(Esercizio29.java:25)

at Esercizio29.ordina(Esercizio29.java:25)

at Esercizio29.ordina(Esercizio29.java:25)

at Esercizio29.main(Esercizio29.java:39)

这个错误是什么意思,我该如何解决?谢谢你。

4

3 回答 3

1

实际上 java.lang.ArrayIndexOutOfBoundsException 意味着您正在访问大于数组大小的数组元素。

例子:

int[] array = {1,2,3,4};

for(int i=0;i<5;i++){
    System.out.println(array[i]);//when i =4 it will show exception.
}

因为我只为数组分配了 4 个元素意味着数组大小为 4。现在,如果我想访问第 5 个元素,它将显示运行时异常,因为数组索引以 0 开头并且数组只有 4 个元素。在第 14 行的情况下,你是访问大于数组大小的数组元素。所以它会导致运行时异常“java.lang.ArrayIndexOutOfBoundsException”

于 2018-06-09T11:46:01.267 回答
1

那么,ArrayIndexOutOfBoundsException错误意味着您试图访问在您的数组中找不到的索引 - 在本例中为索引 1(意味着您的数组在第一个 (0) 索引处包含一个值)。

您的异常是从 join 方法引发的,您确实尝试访问单个大小数组的第二个索引。您对阵列访问操作伙伴没有完整性检查,恐怕这是一种不好的做法......

以下修复将使您的代码按预期运行:

public class Esercizio29 {static void  join(char[] a, int l, int m, int u) {
    char[] b = new char[u]; // replaced redundent [u - 1 + 1]
    int i = l, j = m + 1, k = 0;

    while (i <= m && j <= u) 
        if (a[i] <= a[j])
            b[k++] = a[i++];
        else
            b[k++] = a[j++];
    while (i <= m && k < b.length) // integrity check
        b[k++] = a[i++];
    while (j <= u && k < b.length) { // integrity check
        b[k++] = a[j++];  
    }
    for (k = 0; k <= u - l && k < a.length && k < b.length; k++) // integrity checks
        a[k + l] = b[k];
}
于 2018-06-09T11:53:02.890 回答
1

更改这行代码,它会工作

char[] b = new char[u + 1];

你在哪里做 -1 + 1 导致 ArrayIindexOutOfBounds

于 2018-06-09T11:55:24.027 回答