如何在Java中制作二维产品表数组?

时间:2018-07-18 02:36:49

标签: java arrays

我一直在尝试找出在Java中创建二维数组的正确方法,该数组输出一个N x N平方的乘积表,其中用户输入的任何整数将显示在乘积表结果中。我似乎无法弄清楚如何获取N变量来更改数组内部的大小和结果。我忘了上传自己的代码,因此我将其添加只是为了显示我已经做过的事情...

        int[][] productTable = new int[n][n];
        for (int index = 1; index < n; index++) {
            for (int column =1; column < n; column++) {
                //What now??
            }
        }
        // print format for 2D arrays
        for (int row =0; row < productTable.length; row++) {
            for (int col = 0; col < productTable[row].length; col++)
                System.out.printf("%7d", productTable[row][col]);
            System.out.println();
        }

This is what it should look like if you entered in 4 for N

enter image description here

2 个答案:

答案 0 :(得分:0)

首先,您将需要使用new int[numRows][numCols]语法初始化二维数组。然后,使用嵌套循环遍历每一行和每一列,并用行索引和列索引的乘法填充每个插槽。

public static int[][] makeSquareMultiplicationTable(int sideLength) {
    int[][] table = new int[sideLength][sideLength];
    for (int row = 1; row <= sideLength; row++) {
        for (int col = 1; col <= sideLength; col++) {
            table[row-1][col-1] = row * col;
        }
    }
    return table;
}

答案 1 :(得分:0)

希望它能奏效:)

final int N = 4;
int[][] matrix = new int[N][N];

for(int i = 0; i < N; i++){
    for(int j = 0; j < N; j++){
        matrix[i][j] = (i+1)*(j+1);
    }
}