Java 如何使用用户定义的维度创建矩阵,并使用从上到下、从左到右的递增值填充它?

Java 如何使用用户定义的维度创建矩阵,并使用从上到下、从左到右的递增值填充它?,java,arrays,matrix,multidimensional-array,Java,Arrays,Matrix,Multidimensional Array,我正在练习Java,我得到了这个,我不知道在哪里以及如何继续: 使用用户定义的尺寸创建矩阵 使用从上到下、从左到右递增的值填充矩阵 打印矩阵的状态 我必须达到的结果应该是这样的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 这就是我所做的: publicstati

我正在练习Java,我得到了这个,我不知道在哪里以及如何继续:

  • 使用用户定义的尺寸创建矩阵
  • 使用从上到下、从左到右递增的值填充矩阵
  • 打印矩阵的状态
我必须达到的结果应该是这样的
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
这就是我所做的:

publicstaticvoidmain(字符串[]args){
扫描仪输入=新扫描仪(系统输入);
整数计数=0;
系统输出打印(“插入行[i]:”;
int i=in.nextInt();
in.nextLine();
System.out.println(“插入列[j]:”;
int j=in.nextInt();
in.nextLine();
int[][]矩阵=新的int[i][j];
对于(int k=0;k
您可以使用流中的流填充这样的数组:

intm=5;
int n=4;
int[]arr=新的int[m][n];
IntStream.range(0,m).forEach(i->
IntStream.range(0,n).forEach(j->
arr[i][j]=i+j*m);
Arrays.stream(arr.map)(Arrays::toString.forEach(System.out::println);
//[0, 5, 10, 15]
//[1, 6, 11, 16]
//[2, 7, 12, 17]
//[3, 8, 13, 18]
//[4, 9, 14, 19]

也可以在循环中使用循环:

intm=7;
int n=2;
int[]arr=新的int[m][n];
for(int i=0;i
for(int[]行:arr){
System.out.println(Arrays.toString(row));
}
//[0, 7]
//[1, 8]
//[2, 9]
//[3, 10]
//[4, 11]
//[5, 12]
//[6, 13]


另请参见:

如果您了解工作原理,这并不困难。在内部循环中,可以从等于行索引的值开始,并在内部循环的每次迭代中按行数递增该值

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter the number of rows: ");
        int rows = in.nextInt();

        System.out.print("Enter the number of columns: ");
        int cols = in.nextInt();

        int[][] matrix = new int[rows][cols];

        // Fill the array
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0, value = i; j < matrix[i].length; j++, value += rows) {
                matrix[i][j] = value;
            }
        }

        // Display the matrix
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + "\t");
            }
            System.out.println();
        }
    }
}
另一个示例运行:

Enter the number of rows: 5
Enter the number of columns: 5
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  
Enter the number of rows: 7
Enter the number of columns: 2
0   7   
1   8   
2   9   
3   10  
4   11  
5   12  
6   13