No se puede asignar valor en Java 2D Array - ArrayindexOutofBoundSException
-
24-10-2019 - |
Pregunta
Tengo problemas para asignar un valor a mi matriz 2D en Java. La última línea del código, theGrid[rowLoop][colLoop] = 'x';
, está lanzando un ArrayIndexOutOfBoundsException
error. ¿Alguien podría explicar por qué está sucediendo esto?
Este es mi código ...
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';
}
}
}
}
Solución
Aquí está el problema rowLoop <= theGrid.length
y colLoop <= theGrid[0].length
. Debería ser:
rowLoop < theGrid.length
y
colLoop < theGrid[0].length
La razón del error es porque su índice está llegando a la longitud de la matriz. Entonces, si la longitud era 10, sube al índice 10. Este no es un índice válido en la matriz. Las matrices tienen índices válidos de 0
a length - 1
.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow