How to print Two-Dimensional Array like table

后端 未结 15 936
一整个雨季
一整个雨季 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:37

    You can creat a method that prints the matrix as a table :

    Note: That does not work well on matrices with numbers with many digits and non-square matrices.

        public static void printMatrix(int size,int row,int[][] matrix){
    
                for(int i = 0;i <  7 * size ;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 * size ;i++){ 
                              System.out.print("-");
                         }
                              System.out.println("-");
    
                      }
       }
    
      public static void main(String[] args){
    
         int[][] matrix = {
    
                  {1,2,3,4},
                  {5,6,7,8},
                  {9,10,11,12},
                  {13,14,15,16}
    
    
          };
    
           // print the elements of each row:
    
         int rowsLength = matrix.length;
    
              for(int k = 0; k < rowsLength; k++){
    
                  printMatrix(rowsLength,k,matrix);
              }
    
    
      }
    

    Output :

    ---------------------
    |  1 |  2 |  3 |  4 |
    ---------------------
    |  5 |  6 |  7 |  8 |
    ---------------------
    |  9 | 10 | 11 | 12 |
    ---------------------
    | 13 | 14 | 15 | 16 |
    ---------------------
    

    I created this method while practicing loops and arrays, I'd rather use:

    System.out.println(Arrays.deepToString(matrix).replace("], ", "]\n")));

    0 讨论(0)
  • 2020-11-30 07:40

    More efficient and easy way to print the 2D array in a formatted way:

    Try this:

    public static void print(int[][] puzzle) {
            for (int[] row : puzzle) {
                for (int elem : row) {
                    System.out.printf("%4d", elem);
                }
                System.out.println();
            }
            System.out.println();
        }
    

    Sample Output:

       0   1   2   3
       4   5   6   7
       8   9  10  11
      12  13  14  15
    
    0 讨论(0)
  • 2020-11-30 07:43

    You need to print a new line after each row... System.out.print("\n"), or use println, etc. As it stands you are just printing nothing - System.out.print(""), replace print with println or "" with "\n".

    0 讨论(0)
提交回复
热议问题