繁体   English   中英

对2D数组使用double for循环导致Java中的ArrayIndexOutOfBounds错误

[英]Using a double for loop for a 2D array causing ArrayIndexOutOfBounds error in Java

我正在编写一个程序,计算射弹的行进距离。 给定两个阵列,可能的弹丸发射速度之一,可能的弹丸发射角度之一。 它应该一次遍历它们,然后将输出添加到2D数组中,以便稍后在图形中打印。

for (int i = 0; i < myLaunchSpeeds.length; i++) {

        for (int j = 0; j < myLaunchAngles.length; i++) {

            myLaunchAngles[j] = Math.toRadians(myLaunchAngles[j]);

            myDistances[i][j] = myLaunchSpeeds[i] * Math.sin((2 * myLaunchAngles[j])); //this is where the error is
            myDistances[i][j] = myDistances[i][j] / 9.8;

        }

但是,当我运行它时,出现数组索引超出范围错误。 我该如何解决?

您的第二个循环使用++i ,而应该使用++j

for (int i = 0; i < myLaunchSpeeds.length; i++) {

        for (int j = 0; j < myLaunchAngles.length; i++) {

            myLaunchAngles[j] = Math.toRadians(myLaunchAngles[j]);

            myDistances[i][j] = myLaunchSpeeds[i] * Math.sin((2 * myLaunchAngles[j])); //this is where the error is
            myDistances[i][j] = myDistances[i][j] / 9.8;

        }

问题是您的第二个for循环,您增加了其中的I值(int j = 0; j <myLaunchAngles.length; i ++)。 另外,请确保修复您的缩进,这会使代码更易于阅读和理解。 希望这可以帮助

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM