【问题标题】:Returning An Array From Method To Main Method. Throws An Exception In The Main Method [duplicate]从方法返回一个数组到主方法。在主要方法中引发异常[重复]
【发布时间】:2018-03-21 09:39:10
【问题描述】:

所以我正在尝试创建一个生成随机坐标并将它们存储到数组中的函数。我创建了一个方法,该方法创建并返回了一个数组,其中存储了 2 个随机数。但是,当我运行我的程序时,它会在 main 方法中不断抛出异常。我只想将数组存储在 main 方法中,以便稍后在算法中使用它。

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)

【问题讨论】:

    标签: java arrays exception methods


    【解决方案1】:

    数组索引从0开始,newCoordinate的大小为2,不能通过newCoordinate[2]获取元素。 正确的代码是, System.out.println("一个坐标是(" + newCoordinate[0] + ", " + newCoordinate[1] + ")");

    【讨论】:

    • 非常感谢。这解决了一切。它是否试图访问超出数组长度的数据?这就是它抛出异常的原因吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 2013-11-23
    • 2019-08-06
    • 2016-03-31
    • 2020-06-20
    相关资源
    最近更新 更多