有一个数组超出范围的异常。我该如何解决?

时间:2016-09-15 19:16:47

标签: java arrays sorting exception

我正在尝试编写一个读取数据文件并将整数读入标准整数数组(而不是ArrayList)的Java程序,对数组进行排序,并显示从最低到最高的值。我还需要编写一个使用冒泡排序或选择排序来进行排序的排序函数。我一直收到这个错误:" java.lang.ArrayIndexOutOfBoundsException:8"在第39和52行。我该如何解决这个问题?

public static void main(String[] args) {
    // TODO Auto-generated method stub

    // Declaring variables
    String name;

    // Declaring scanner for name of file
    Scanner iscanner = new Scanner(System.in);

    // Reading in file name
    System.out.println("What is the name of your file?" );
    name = iscanner.next();

    java.io.File file = new java.io.File(name);

    // Declaring scanner for inside the file
    Scanner inp;

    try {

        // Assigning scanner to the file
        inp = new Scanner(file);

        // Declaring array
        int [] nums = new int [(int) name.length()];

        // Reading integers into array
        for (int i =0; i < name.length(); i++)
        {
            nums[i] = inp.nextInt();
        }
        // THIS IS LINE 39*****************
        // Calling sorting function
        bubblesort(nums);

    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

static void bubblesort(int[] nums){
    int temp;
    for (int i = 0; i < nums.length; i++)
    { // THIS IS LINE 52**************************
        for (int j = 0; j < nums.length; j++)
        {
            if(nums[i] > nums[j+1])
            {
                temp = nums[j+1];
                nums[j+1] = nums[i];
                nums[i] = temp;
            }
        }
    }

    for(int i = 0; i < nums.length; i++)
    {
        System.out.println(nums[i]);
    }

}

1 个答案:

答案 0 :(得分:1)

由于您使用j + 1,您将获得一个超出范围的数组异常。您的内部循环计数最多为nums.length - 1,然后您将其添加到nums.length。因此,您正在访问j < nums.length - 1处的数组,这会导致异常。要解决此问题,请调整阵列上的边界,例如停在page.10 = COA_INT page.10 { 10 = CONTENT 10 { table = pages select { orderBy = rand() max = 1 pidInList = 34 } renderObj = COA renderObj { 5 = FILES 5 { references { table = pages uid.data = current:uid fieldName = media } begin = 0 maxItems = 1 renderObj = IMAGE renderObj { file.import.data = file:current:publicUrl } } } } }