Search code examples
javaeclipseindexoutofboundsexception

ArrayIndexOutOfBoundsExecption on RangeFinder program


The program I am posting is supposed to make the user create an array, then add integer values into it.

The program will call a method to find the range of the array then print the returned value along with printing the array.

However, I'm getting an ArrayIndexOutOfBoundsExecption when I try and run it

`

import java.util.*; public class RangeFinder {

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

} `


Solution

  • This is selecting outside the bounds of the array:

    int largest = testArray[array.length];
    

    For example, if the length of the array of 10 then the indexes are from 0 to 9. Trying to select item testArray[10] is an error. You want to subtract 1 from the length to get the last element:

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