-4

So I am trying to create a function that generates random coordinates and stores them into an array. I created a method that created and returned an array with 2 random numbers stored in it. However when I run my program, it keeps throwing an exception in the main method. I just want store the array in the main method so I can use it in an algorithm later.

public static void main (String[] args) {
    //This initializes each coordinate used
    int[] firstCoordinate = randomCoordinates();  //This is line four where
    int[] secondCoordinate = randomCoordinates(); // the exception is thrown        

    //end of main method
}

public static int[] randomCoordinates() {
     int[] newCoordinate = new int[2];
     for (int i = 0; i < newCoordinate.length; i++) {
         newCoordinate[i] = (int) (Math.random() * 100 + 1);
     }
     System.out.println("One coordinate is (" + newCoordinate[1] + ", " + newCoordinate[2] + ")");            //Exception also thrown here.
     return newCoordinate;
}

The exception states: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at BetterDIAZR18.randomCoordinates(BetterDIAZR18.java:21) at BetterDIAZR18.main(BetterDIAZR18.java:4)

1 Answers1

0

Array index starts from 0. The size of newCoordinate is 2, you cannot get element by newCoordinate[2]. Right code is, System.out.println("One coordinate is (" + newCoordinate[0] + ", " + newCoordinate[1] + ")");

kingston
  • 1
  • 2
  • Thank you very much. That fixed everything. Was it trying to access the data that was past the array's length? Was that why it was throwing the exception? – The Brogrammer Oct 10 '17 at 05:20