数组索引越界异常,当我运行它时,我无法弄清楚原因。我无法查看已排序的数组

时间:2015-04-11 13:58:15

标签: java arrays algorithm exception

import java.util.Scanner;

public class Sort {
    public void Countsort(int a[], int b[], int k) throws ArrayIndexOutOfBoundsException {
        int[] c = new int[k + 1];
        for (int i = 0; i < k; i++) {
            c[i] = 0;
        }

        for (int i = 0; i <= a.length; i++) {
            c[a[i]] = c[a[i]] + 1;
        }

        for (int i = 1; i <= k; i++) {
            c[i] = c[i] + c[i - 1];
        }

        for (int i = a.length; i <= 1; i--) {
            b[c[a[i]]] = a[i];
            c[a[i]] = c[a[i]] - 1;
        }
    }

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int num;
        int[] temp = new int[10000];
        int i = 0;
        while (sc.hasNextInt()) {
            num = sc.nextInt();
            temp[i] = num;
            i++;
            if (num == -1) {
                break;
            }
        }

        int A[] = new int[i];

        // just a check
        for (i = 0; i < temp.length; i++) {
            System.out.println("temp values:" + temp[i]);
        }
        // just a check ends

        for (int j = 0; j < A.length; j++) {
            A[j] = temp[j];
            System.out.println("tem copied vals:" + A[j]);
        }

        // a check for gthat a has temp values..    
        int[] B = new int[A.length];
        new Sort().Countsort(A, B, 100);

        for (i = 0; i < B.length; i++) {
            System.out.println("Run count #" + i + " : " + B[i]);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

首先你的while循环应该是

 while (sc.hasNextInt()) {
            num = sc.nextInt();
            if (num == -1) {
                break; 
            }
// so that you can stop -1 to be stored
            temp[i] = num;
            i++;

        }

接下来就是你的循环

for (int i = 0; i < a.length; i++) { // always less than length of the array 
            c[a[i]] = c[a[i]] + 1;
        }