java - 无法加载二维数组

标签 java arrays loops nested-loops

第一个 for 循环似乎只执行一次,而第二个(内部)for 循环工作正常。 我尝试了我知道的每种类型的循环,但总是得到相同的结果。 我通常不会遇到这些循环问题,所以我很好奇问题可能是什么。

    public class xirtam {

        public static void main(String[] args) {

            try {

                int max_columns = 10;
                int max_characters_in_a_column = 30, sign;
                int array[][] = new int[max_columns][max_characters_in_a_column];


                for(int y=0;y<=max_columns;y++) {  

> // This loop seems to be executed just 1 time


                    for (int x=0 ; x<=max_characters_in_a_column ; x++) {  

> //This loop works fine for some reason


                        sign = (int) (Math.random() * ((256 - 0) + 1));

                        array[y][x] = sign;

                        System.out.println("column " + y + " character " + x + ":"+ array[y][x]); // prints out the "column" and "character" where the loop is currently working

                        //Thread.sleep(100);
                    }

                }

            } catch (Exception e) {
            }

        }
    }

最佳答案

您获得了 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 30 out of bounds for length 30array[y][x] = sign; 。因此。

在第二个 for 循环中使用 x<max_characters_in_a_column不是<= 。这将解决您的问题。第一个循环也是如此。

数组的最大索引为 array[9][29] ,因为您已将尺寸定义为 10 和 30。

关于java - 无法加载二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58555735/

相关文章:

arrays - Perl,将数组 : adding and removing keys, 的散列添加到数组中,全部在 while 循环中

Jquery 循环选择器和单击事件处理程序

java - Android NFS 客户端

java - Angular 火 : How to perform some operations on data before updating template

Java:第一次添加调用时触发 TreeSet compareTo 方法

java - Java 和 C 不用套接字进行通信?

ios - 设置从数组中选择的按钮的标题 - Xcode iOS

java - 如何根据条件取消选择二维数组中的一行并查找其他行的总和

algorithm - 避免在 2D 游戏引擎中嵌套 for 循环

Python - 如果包含列表中元组的元素,则仅打印行