java如何创建具有用户定义维度的矩阵,并使用从上到下、从左到右的递增值填充它?
我正在练习Java,我得到了这个,我不知道在哪里以及如何继续:
- Creates a matrix with user-defined dimensions.
- Fills the matrix with increasing values from top to bottom, left to right.
- Print the status of the matrix.
我必须达到的结果应该是这样的5x5
:
0 5 10 15 20
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
或者这个7x2
:
0 7
1 8
2 9
3 10
4 11
5 12
6 13
这就是我所做的:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int count = 0;
System.out.print("Insert rows [i] : ");
int i = in.nextInt();
in.nextLine();
System.out.println("Insert columns [j] : ");
int j = in.nextInt();
in.nextLine();
int[][] matrix = new int[i][j];
for (int k = 0; k < matrix.length; k++) {
for (int l = 0; l < matrix[i].length; l++) {
matrix[i][j] = count;
count++;
}
}
}
# 1 楼答案
如果你理解nested loops是如何工作的,这并不困难。在内部循环中,可以从等于行索引的值开始,并在内部循环的每次迭代中按行数递增该值
运行示例:
另一个示例运行:
# 2 楼答案
您可以使用流中的流来填充这样的数组:
或者您可以在循环中使用循环:
另见:Printing a snake pattern using an array