avi
avi

Reputation: 1877

How to correctly initialize multi dimensional arrays dynamically in Java?

Q. How to initialize arrays dynamically in Java?

I'm trying to store some metrics in arrays by using the following code.

 public static void main (String[] args) {
    Scanner in = new Scanner(System.in);
    int t = in.nextInt(); // outer metric size 
    int [] n = new int[t]; // inner square metric e.g. 3x3
    int [][][] a = new int[t][][]; // e.g. 2x3x3, 10x3x3

    //input block
    for (int h=0; h<t; h++){
        n[h] = in.nextInt(); //inner square metric dimensions
        for (int i=0;i<n[h];i++){
            for (int j=0;j<n[h];j++){
                a[h][i][j] = in.nextInt();    //metric values
            }
        }
    }

results in Null Pointer Exception which in turn is an array reference expected error. Changing the arrays to fixed size, doesn't cause this issue as expected.

  int [] n = new int[70];
  int [][][] a = new int[70][10][10];

Therefore, I would like to understand the right way to initialize dynamic arrays.

Upvotes: 0

Views: 132

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201439

You have to allocate a new int[][] in the outer loop. Something like,

n[h] = in.nextInt(); //inner square metric dimensions
a[h] = new int[n[h]][n[h]]; //add this

Upvotes: 1

Related Questions