Mar*_*1ow 1 java arrays indexoutofboundsexception
我在使用Java为我的2D数组赋值时遇到了麻烦.代码的最后一行theGrid[rowLoop][colLoop] = 'x';是抛出ArrayIndexOutOfBoundsException错误.有人可以解释为什么会这样吗?
这是我的代码......
public class Main {
public static char[][] theGrid;
public static void main(String[] args) {
createAndFillGrid(10,10);
}
public static void createAndFillGrid(int rows, int cols) {
theGrid = new char[rows][cols];
int rowLoop = 0;
for (rowLoop = 0; rowLoop <= theGrid.length; rowLoop++) {
int colLoop = 0;
for (colLoop = 0; colLoop <= theGrid[0].length; colLoop++) {
theGrid[rowLoop][colLoop] = 'x';
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是问题所在rowLoop <= theGrid.length和colLoop <= theGrid[0].length.它应该是:
rowLoop < theGrid.length
Run Code Online (Sandbox Code Playgroud)
和
colLoop < theGrid[0].length
Run Code Online (Sandbox Code Playgroud)
出错的原因是因为您的索引达到了数组的长度.因此,如果长度为10,则上升到索引10.这不是数组的有效索引.阵列具有有效索引0到length - 1.
| 归档时间: |
|
| 查看次数: |
1221 次 |
| 最近记录: |