简体   繁体   English

如何在Java中动态地正确初始化多维数组?

[英]How to correctly initialize multi dimensional arrays dynamically in Java?

Q. How to initialize arrays dynamically in Java? 问:如何在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. 导致Null指针异常,这又是数组引用预期的错误。 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. 因此,我想了解初始化动态数组的正确方法。

You have to allocate a new int[][] in the outer loop. 您必须在外部循环中分配新的int[][] Something like, 就像是,

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM