printing out a 2-D array in Matrix format

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

    Here's my efficient approach for displaying 2-D integer array using a StringBuilder array.

    public static void printMatrix(int[][] arr) {
        if (null == arr || arr.length == 0) {
            // empty or null matrix
            return;
        }
    
        int idx = -1;
        StringBuilder[] sbArr = new StringBuilder[arr.length];
    
        for (int[] row : arr) {
            sbArr[++idx] = new StringBuilder("(\t");
    
            for (int elem : row) {
                sbArr[idx].append(elem + "\t");
            }
    
            sbArr[idx].append(")");
        }
    
        for (int i = 0; i < sbArr.length; i++) {
            System.out.println(sbArr[i]);
        }
        System.out.println("\nDONE\n");
    }
    

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 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<int[]> noDelimiter = (row) -> {
                Arrays.stream(row).forEach((el) -> System.out.print(" " + el + " "));
                System.out.println();
            };
    
            Consumer<int[]> pipeDelimiter = (row) -> {
                Arrays.stream(row).forEach((el) -> System.out.print("| " + el + " "));
                System.out.println("|");
            };
    
            Consumer<int[]> 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<int[]> 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 ]
    
    0 讨论(0)
  • 2020-12-08 03:45
        int[][] matrix = {
            {1,2,3},
            {4,5,6},
            {7,8,9}
        };
        //use foreach loop as below to avoid IndexOutOfBoundException
        //need to check matrix != null if implements as a method
        //for each row in the matrix
        for (int[] row : matrix) {
            //for each number in the row
            for (int j : row) {
                System.out.print(j + " ");
            }
            System.out.println("");
        }
    
    0 讨论(0)
  • 2020-12-08 03:49
    final int[][] matrix = {
      { 1, 2, 3 },
      { 4, 5, 6 },
      { 7, 8, 9 }
    };
    
    for (int i = 0; i < matrix.length; i++) {
        for (int j = 0; j < matrix[i].length; j++) {
            System.out.print(matrix[i][j] + " ");
        }
        System.out.println();
    }
    

    Produces:

    1 2 3
    4 5 6
    7 8 9
    
    0 讨论(0)
  • 2020-12-08 03:50
    public static void main(String[] args) 
            {
                 int [] [] ar= 
                    {
                            {12,33,23},
                            {34,56,75},
                            {14,76,89},
                            {45,87,20}
    
                    };
    

    I prefer using enhanced loop in Java

    Since our ar is an array of array [2D]. So, when you iterate over it, you will first get an array, and then you can iterate over that array to get individual elements.

                 for(int[] num: ar)
                 {
                     for(int ele : num)
                     {
                     System.out.print(" " +ele);
                     }
                     System.out.println(" " );
                 }
    
                  }
    
    0 讨论(0)
提交回复
热议问题