无法加载二维数组
Can´t load a two dimensional array
第一个 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) {
}
}
}
您在 array[y][x] = sign;
获得了 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 30 out of bounds for length 30
。这就是为什么。
在你的第二个 for 循环中使用 x<max_characters_in_a_column
而不是 <=
。这将解决您的问题。第一个循环也一样。
数组的最大索引将为 array[9][29]
,因为您已将维度定义为 10 和 30。
第一个 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) {
}
}
}
您在 array[y][x] = sign;
获得了 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 30 out of bounds for length 30
。这就是为什么。
在你的第二个 for 循环中使用 x<max_characters_in_a_column
而不是 <=
。这将解决您的问题。第一个循环也一样。
数组的最大索引将为 array[9][29]
,因为您已将维度定义为 10 和 30。