简体   繁体   English

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

[英]Having an array out of bounds exception. How do i fix this?

I am trying to write a Java program that reads in a data file and reads the integers into a standard integer array (not an ArrayList), sorts the array, and displays the values from lowest to highest. 我正在尝试编写一个Java程序,该程序读取数据文件并将整数读入标准整数数组(而不是ArrayList)中,对数组进行排序,并显示从最低到最高的值。 I also need to write a sort function that uses bubble sort or selection sort to do the sorting. 我还需要编写一个排序函数,该函数使用冒泡排序或选择排序进行排序。 I keep getting this error: "java.lang.ArrayIndexOutOfBoundsException: 8" in lines 39 and 52. How do I fix this? 我不断在第39和52行收到此错误:“ java.lang.ArrayIndexOutOfBoundsException:8”。如何解决此问题?

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]);
    }

}

You're getting an array out of bounds exception due to your use of j + 1 . 由于使用j + 1因此出现数组超出范围的异常。 Your inner loop counts up to nums.length - 1 , which you then add one to. 您的内部循环最多计数nums.length - 1 ,然后将其加1。 Thus, you're accessing the array at nums.length , which causes the exception. 因此,您正在访问nums.length的数组,这将导致异常。 To fix this, adjust your bounds on the array, such as stopping at j < nums.length - 1 . 要解决此问题,请调整数组的边界,例如在j < nums.length - 1处停止。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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