I'm trying to create a simple program that allows me to create 2d arrays with different objects.
My thought process was that I should be able to create objects with arguments (as declared at the beginning of the class and referred to in the constructor) and would automatically create an array with the dimensionm => linhas; n => colunas
, passed as constructor parameters object. So I tried to give values directly to every cell in the array.
So here's the code:
public class Matrix {
Scanner ler = new Scanner (System.in);
int m;
int n;
int [][] arr = new int[m][n];
Matrix(int a, int b){
m = a;
n = b;
}
public static void main(String[] args) {
Matriz m1 = new Matrix(3,2);
//System.out.println(m1.m +" "+ m1.n); -> Mostra corretamente os valores "3" e "2"
m1.arr[0][0] = 1;
m1.arr[1][1] = 1;
m1.arr[2][0] = 1;
m1.arr[0][1] = 1;
m1.arr[1][0] = 1;
m1.arr[2][1] = 1;
//Matrix m2 = new Matrix(3,2);
}
}
Netbeans did not show any errors, but when I tried to run the program, I received the following message:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at pack1.Matrix.extra (Matrix.java:32) at package1.Matrix.main (Matrix.java:43) C: \ Users \ me \ AppData \ Local \ NetBeans \ Cache \ 8.2 \ executor-snippets \ run.xml: 53: Java returned: 1 BUILD FAILED (total time: 0 seconds)
When I looked for this error here in stackoverflow, I began to understand that this error means that I'm trying to access an index that does not exist in the array, and that should mean I was unsuccessful in trying to give values to 'm' and 'n 'as object arguments.
How to solve this?