Attempting to create two-dimensional arrays as objects

2

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 dimension m => 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?

    
asked by anonymous 12.08.2017 / 18:30

1 answer

1

The problem with your code is that you start the array before receiving the values to define its size, and this is a consequence of java class start order . Because the m and n variables are primitives of type int and are not initialized, the default initialization value set for them it is 0 and they end up starting the array with dimension 0x0. Passing the array creation to the constructor as below, it will only start the array after m and n receive the desired values for its dimension.

See the corrected code:

public class Matrix {

    Scanner ler = new Scanner (System.in);   
    int m;
    int n;
    int [][] arr;

    Matrix(int a, int b){
        m = a;
        n = b;
        arr = new int[m][n];
    }


    public static void main(String[] args) {

      Matrix 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);

    }
}

See working at ideone: link

    
12.08.2017 / 18:49