2
I’m trying to create a simple program that allows me to create 2d (matrix) matrices with different objects.
My thought process was that I should be able to create objects with arguments (as stated at the beginning of the class and referred to in the constructor) and that would automatically create a matrix with the dimension m => linhas; n => colunas
, passed as object constructor parameters. So, I tried to give values directly to each matrix cell.
So this is 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 showed no errors, but when I tried to run the program, I got the following message:
Exception in thread "main" java.lang.Arrayindexoutofboundsexception: 0 at pacote1.Matriz.extra(Matrix.java:32) at pacote1.Matriz.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 started to understand that this error means that I am trying to access an index that does not exist in the matrix, and it must mean that I did not succeed in trying to give values to’m' and 'n' as object arguments.
How to solve this?
Solved. Thank you very much :)
– António Faneca