Java ArrayIndexOutOfBoundsExecption测距仪程序

Java ArrayIndexOutOfBoundsExecption测距仪程序,java,eclipse,indexoutofboundsexception,Java,Eclipse,Indexoutofboundsexception,我发布的程序应该让用户创建一个数组,然后向其中添加整数值 程序将调用一个方法来查找数组的范围,然后在打印数组的同时打印返回值 然而,当我尝试运行它时,我得到了一个ArrayIndexOutOfBoundsExecption ` 导入java.util.*; 公共级测距仪{ public static void main(String[] args) { System.out.println("Please enter the length of your array: ");

我发布的程序应该让用户创建一个数组,然后向其中添加整数值

程序将调用一个方法来查找数组的范围,然后在打印数组的同时打印返回值

然而,当我尝试运行它时,我得到了一个ArrayIndexOutOfBoundsExecption

`

导入java.util.*; 公共级测距仪{

public static void main(String[] args) {

    System.out.println("Please enter the length of your array: ");
    Scanner sc = new Scanner(System.in);
    int size = sc.nextInt();
    int[] userArray = new int[size];

    for (int i = 0; i != size; i++) {
        System.out.println("Please enter the number for your array[" + (i+1) + "]: ");
        int temp = sc.nextInt();
        userArray[i] = temp;

    }

    RangeFinder.range(userArray);

    System.out.println();
    System.out.println(Arrays.toString(userArray));
    System.out.println(RangeFinder.range(userArray));


}



public static int range(int[] array) {

     int[] testArray = array;
     Arrays.sort(testArray);
     int smallest = testArray[0];
     int largest = testArray[array.length];

    int range = largest - smallest;


    return range;
  }
}
`

这是在数组边界之外选择:

int largest = testArray[array.length];
例如,如果
10
数组的长度,则索引从
0
9
。尝试选择项
testArray[10]
时出错。您想从长度中减去
1
,得到最后一个元素:

int largest = testArray[array.length - 1];