如何使用2D数组创建矩阵

时间:2018-08-23 07:17:22

标签: java

我正在尝试创建一个6x3矩阵,该矩阵每次在列第一行和第二行上迭代时都会增加一个。

这是我目前拥有的代码:

public static void main(String[] arg) {

    int[][] mat1 = new int[6][3];
    for(int i = 1; i < mat1.length; i++) {
        for(int j = 0; j < mat1[i].length; j++) {
            mat1[i][j] = i + j;
            System.out.print(mat1[i][j] + " ");
        }
        System.out.println();
    }
}

现在我得到输出:

1 2 3 
2 3 4 
3 4 5 
4 5 6 
5 6 7 

所需的输出是:

1 2 3
4 5 6
7 8 9
10 11 12
13 14 15
16 17 18

我该怎么做?

2 个答案:

答案 0 :(得分:2)

想要生成一个从0、1、2,.. 17开始计数的“序列”。 您的问题是i+j不会生成该序列。

因此:

mat1[i][j] = i + j;

只是加计数。一个更简单的解决方案是:

mat1[i][j] = overallCounter++;

(并且overallCounter被声明为int overallCounter = 0 在外部for循环之前

)。

旁注:并且正如注释正确指出的那样:我也应该从0开始。数组在Java中是从0开始的!

答案 1 :(得分:1)

您得到的输出是正确的:

On the first iteration, i = 1 and j = 0, so i+j = 1
On the 4th iteration i = 2 and j = 0, so i+j = 2
On the 7th iteration i = 3 and j = 0, so i+j = 3

这是您解决问题的方法

public static void main(String[] arg) {

  int[][] mat1 = new int[6][3];
  int counter = 1;
    for(int i = 0; i < mat1.length; i++) {
        for(int j = 0; j < mat1[i].length; j++) {
            mat1[i][j] = counter;
            counter++;
            System.out.print(mat1[i][j] + " ");
        }
        System.out.println();
    }
}