How to print Two-Dimensional Array like table

后端 未结 15 1114
一整个雨季
一整个雨季 2020-11-30 06:55

I\'m having a problem with two dimensional array. I\'m having a display like this:

1 2 3 4 5 6 7 9 10 11 12 13 14 15 16 . . . etc

What basi

15条回答
  •  情话喂你
    2020-11-30 07:21

    Iliya,

    Sorry for that.

    you code is work. but its had some problem with Array row and columns

    here i correct your code this work correctly, you can try this ..

    public static void printMatrix(int size, int row, int[][] matrix) {
    
        for (int i = 0; i < 7 * matrix[row].length; i++) {
            System.out.print("-");
        }
        System.out.println("-");
    
        for (int i = 1; i <= matrix[row].length; i++) {
            System.out.printf("| %4d ", matrix[row][i - 1]);
        }
        System.out.println("|");
    
        if (row == size - 1) {
    
            // when we reach the last row,
            // print bottom line "---------"
    
            for (int i = 0; i < 7 * matrix[row].length; i++) {
                System.out.print("-");
            }
            System.out.println("-");
    
        }
    }
    
    public static void length(int[][] matrix) {
    
        int rowsLength = matrix.length;
    
        for (int k = 0; k < rowsLength; k++) {
    
            printMatrix(rowsLength, k, matrix);
    
        }
    
    }
    
    public static void main(String[] args) {
    
        int[][] matrix = { { 1, 2, 5 }, { 3, 4, 6 }, { 7, 8, 9 }
    
        };
    
        length(matrix);
    
    }
    

    and out put look like

    ----------------------
    |    1 |    2 |    5 |
    ----------------------
    |    3 |    4 |    6 |
    ----------------------
    |    7 |    8 |    9 |
    ----------------------
    

提交回复
热议问题