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)