printing out a 2-D array in Matrix format

后端 未结 9 1398
暖寄归人
暖寄归人 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:35

    To properly format numbers in columns, it's best to use printf. Depending on how big are the max or min numbers, you might want to adjust the pattern "%4d". For instance to allow any integer between Integer.MIN_VALUE and Integer.MAX_VALUE, use "%12d".

    public void printMatrix(int[][] matrix) {
        for (int row = 0; row < matrix.length; row++) {
            for (int col = 0; col < matrix[row].length; col++) {
                System.out.printf("%4d", matrix[row][col]);
            }
            System.out.println();
        }
    }
    

    Example output:

     36 913 888 908
    732 626  61 237
      5   8  50 265
    192 232 129 307
    

提交回复
热议问题