我正在尝试创建一个6x3的矩阵,每次您在第一列和第二列上进行迭代时,矩阵每次增加1。
这是我目前拥有的代码:
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
我将如何去做呢?
最佳答案
您想要生成一个从0、1、2,.. 17开始计数的“序列”。
您的问题是i+j
不会生成该序列。
因此:
mat1[i][j] = i + j;
根本不算数。一个更简单的解决方案是:
mat1[i][j] = overallCounter++;
(并且
overallCounter
在外部for循环之前声明为int overallCounter = 0
)。旁注:正如评论正确指出的那样:我也应该从0开始。数组在Java中从0开始!
关于java - 如何使用2D数组创建矩阵,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51980278/