Java 将数组从方法返回到主方法。在主方法中引发异常
所以我试图创建一个函数,生成随机坐标并将它们存储到数组中。我创建了一个方法,该方法创建并返回一个数组,其中存储了2个随机数。但是,当我运行程序时,它会在main方法中不断抛出异常。我只想将数组存储在main方法中,以便在以后的算法中使用它Java 将数组从方法返回到主方法。在主方法中引发异常,java,arrays,exception,methods,Java,Arrays,Exception,Methods,所以我试图创建一个函数,生成随机坐标并将它们存储到数组中。我创建了一个方法,该方法创建并返回一个数组,其中存储了2个随机数。但是,当我运行程序时,它会在main方法中不断抛出异常。我只想将数组存储在main方法中,以便在以后的算法中使用它 public static void main (String[] args) { //This initializes each coordinate used int[] firstCoordinate = randomCoordinate
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;
}
例外情况说明:
主线程java.lang.ArrayIndexOutOfBoundsException中的异常:2
在BetterDIAZR18.RandomCoordinates BetterDIAZR18.java:21
在BetterDIAZR18.main上BetterDIAZR18.java:4数组索引从0开始。newCoordinate的大小为2,不能通过newCoordinate[2]获取元素。 正确的代码是,
System.out.printlnOne坐标为+新坐标[0]+,+新坐标[1]+ 多谢各位。一切都解决了。它是否试图访问超过数组长度的数据?这就是它抛出异常的原因吗?