考虑:

int[][] multD = new int[5][];
multD[0] = new int[10];

这就是创建5行10列的二维数组的方法吗?

我在网上看到了这段代码,但语法没有意义。


当前回答

试试下面的方法:

int[][] multi = new int[5][10];

... 这是类似这样的东西的简称:

int[][] multi = new int[5][];
multi[0] = new int[10];
multi[1] = new int[10];
multi[2] = new int[10];
multi[3] = new int[10];
multi[4] = new int[10];

注意,每个元素都将被初始化为int, 0的默认值,因此上述也等价于:

int[][] multi = new int[][]{
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};

其他回答

int rows = 5;
int cols = 10;

int[] multD = new int[rows * cols];

for (int r = 0; r < rows; r++)
{
  for (int c = 0; c < cols; c++)
  {
     int index = r * cols + c;
     multD[index] = index * 2;
  }
}

享受吧!

您可以按照其他人提到的方法创建它们。还有一点需要补充:你甚至可以用每一行创建一个倾斜的二维数组,不一定有相同数量的列,就像这样:

int array[][] = new int[3][];
array[0] = new int[3];
array[1] = new int[2];
array[2] = new int[5];
int [][] twoDim = new int [5][5];

int a = (twoDim.length);//5
int b = (twoDim[0].length);//5

for(int i = 0; i < a; i++){ // 1 2 3 4 5
    for(int j = 0; j <b; j++) { // 1 2 3 4 5
        int x = (i+1)*(j+1);
        twoDim[i][j] = x;
        if (x<10) {
            System.out.print(" " + x + " ");
        } else {
            System.out.print(x + " ");
        }
    }//end of for J
    System.out.println();
}//end of for i

也可以用以下方式声明它。这不是什么好设计,但很管用。

int[] twoDimIntArray[] = new int[5][10];

试试下面的方法:

int[][] multi = new int[5][10];

... 这是类似这样的东西的简称:

int[][] multi = new int[5][];
multi[0] = new int[10];
multi[1] = new int[10];
multi[2] = new int[10];
multi[3] = new int[10];
multi[4] = new int[10];

注意,每个元素都将被初始化为int, 0的默认值,因此上述也等价于:

int[][] multi = new int[][]{
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },
  { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};