printing out a 2-D array in Matrix format

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

    In java8 fashion:

    import java.util.Arrays;
    
    public class MatrixPrinter {
    
        public static void main(String[] args) {
            final int[][] matrix = new int[4][4];
            printMatrix(matrix);
        }
    
        public static void printMatrix(int[][] matrix) {
            Arrays.stream(matrix)
            .forEach(
                (row) -> {
                    System.out.print("[");
                    Arrays.stream(row)
                    .forEach((el) -> System.out.print(" " + el + " "));
                    System.out.println("]");
                }
            );
        }
    
    }
    

    this produces

    [ 0  0  0  0 ]
    [ 0  0  0  0 ]
    [ 0  0  0  0 ]
    [ 0  0  0  0 ]
    

    but since we are here why not make the row layout customisable?

    All we need is to pass a lamba to the matrixPrinter method:

    import java.util.Arrays;
    import java.util.function.Consumer;
    
    public class MatrixPrinter {
    
        public static void main(String[] args) {
            final int[][] matrix = new int[3][3];
    
            Consumer noDelimiter = (row) -> {
                Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
                System.out.println();
            };
    
            Consumer pipeDelimiter = (row) -> {
                Arrays.stream(row).forEach((el) -> System.out.print("| " + el + " "));
                System.out.println("|");
            };
    
            Consumer likeAList = (row) -> {
                System.out.print("[");
                Arrays.stream(row)
                .forEach((el) -> System.out.print(" " + el + " "));
                System.out.println("]");
            };
    
            printMatrix(matrix, noDelimiter);
            System.out.println();
            printMatrix(matrix, pipeDelimiter);
            System.out.println();
            printMatrix(matrix, likeAList);
    
        }
    
        public static void printMatrix(int[][] matrix, Consumer rowPrinter) {
            Arrays.stream(matrix)
            .forEach((row) -> rowPrinter.accept(row));
        }
    
    }
    

    this is the result :

     0  0  0 
     0  0  0 
     0  0  0 
    
    | 0 | 0 | 0 |
    | 0 | 0 | 0 |
    | 0 | 0 | 0 |
    
    [ 0  0  0 ]
    [ 0  0  0 ]
    [ 0  0  0 ]
    

提交回复
热议问题