What is wrong here? I get an runtime error when I run the code in Netbeans saying “java.lang.ArrayIndexOutOfBoundsException: 0”
I found out it means something like “the value does not exist” – but that is what I am trying to do – to let the user define the values for the array size. Help, please.
public static void main(String[] args) {
int row = 0;
int colum = 0;
//Declare 2d array
int [][] matrix = new int [row][colum];
//Create input for array size
Scanner input = new Scanner(System.in);
System.out.println("Enter " + matrix[row].length + " rows and " + matrix[colum].length + " colums: ");
for (row = 0; row < matrix.length; row++) {
for (colum = 0; colum < matrix[row].length ; colum++) {
matrix[row][colum] = input.nextInt();
//Input variables to array
//Print the array
for (row = 0; row < matrix.length; row++ ) {
for (colum = 0; colum < matrix[row].length; colum++ ) {
System.out.println(matrix[row][colum] + "");
}
System.out.println();
}
}
}
}
}
Two problems. You need to initialize row and column with non-zero values:
You’re not referencing the dimensions of the matrix correctly, you want:
There are a few more bad references further down. You could of course just use your
rowandcolumnvariables instead of getting the lengths from thematrixthough.