printing out a 2-D array in Matrix format

后端 未结 9 1442
暖寄归人
暖寄归人 2020-12-08 03:13

How can I print out a simple int [][] in the matrix box format like the format in which we handwrite matrices in. A simple run of loops doesn\'t apparently work. If it helps

9条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 03:55

    public static void printMatrix(double[][] matrix) {
        for (double[] row : matrix) {
            for (double element : row) {
                System.out.printf("%5.1f", element);
            }
            System.out.println();
        }
    }
    

    Function Call

    printMatrix(new double[][]{2,0,0},{0,2,0},{0,0,3}});
    

    Output:

      2.0  0.0  0.0
      0.0  2.0  0.0
      0.0  0.0  3.0
    

    In console:

提交回复
热议问题