第一个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) {
}
}
}
答案 0 :(得分:3)
您在Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 30 out of bounds for length 30
有array[y][x] = sign;
。这就是为什么。
在第二个for循环中,使用x<max_characters_in_a_column
而不是<=
。这样可以解决您的问题。第一次循环也是一样。
由于将维度定义为10和30,因此数组的最大索引为array[9][29]
。