printing out a 2-D array in Matrix format

后端 未结 9 1400
暖寄归人
暖寄归人 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:55
    public static void printMatrix(double[][] matrix) {
        for (double[] row : matrix) {
            for (double element : row) {
                System.out.printf("%5.1f", element);
            }
            System.out.println();
        }
    }
    

    Function Call

    printMatrix(new double[][]{2,0,0},{0,2,0},{0,0,3}});
    

    Output:

      2.0  0.0  0.0
      0.0  2.0  0.0
      0.0  0.0  3.0
    

    In console:

    0 讨论(0)
  • 2020-12-08 03:55
    public class Matrix 
    {
       public static void main(String[] args)
       {
          double Matrix [] []={
             {0*1,0*2,0*3,0*4),
             {0*1,1*1,2*1,3*1),
             {0*2,1*2,2*2,3*2),
             {0*3,1*3,2*3,3*3)
          };
    
          int i,j;
          for(i=0;i<4;i++)
          {
             for(j=0;j<4;j++)
                System.out.print(Matrix [i] [j] + " ");
             System.out.println();
          }
       }
    }
    
    0 讨论(0)
  • 2020-12-08 03:59
    int[][] matrix = {
        {1,2,3},
        {4,5,6},
        {7,8,9},
        {10,11,12}
    };
    
    printMatrix(matrix);
    
    public void printMatrix(int[][] m){
        try{
            int rows = m.length;
            int columns = m[0].length;
            String str = "|\t";
    
            for(int i=0;i<rows;i++){
                for(int j=0;j<columns;j++){
                    str += m[i][j] + "\t";
                }
    
                System.out.println(str + "|");
                str = "|\t";
            }
    
        }catch(Exception e){System.out.println("Matrix is empty!!");}
    }
    

    Output:

    |   1   2   3   |
    |   4   5   6   |
    |   7   8   9   |
    |   10  11  12  |
    
    0 讨论(0)
提交回复
热议问题