【问题标题】:How to format an array so it will look like a matrix when printing?如何格式化数组,使其在打印时看起来像矩阵?
【发布时间】:2015-03-15 15:02:43
【问题描述】:

如何格式化二维数组,以便打印出一种矩阵“样式”。

例如,在这个代码数组的 sn-p 中,得到两个二维 int 数组的乘积。

说一个像这样的 2x2 矩阵

   59 96

   78 51

在打印出来的命令提示符中,它最终会像这样显示

59 96 78 51

如何让它以行列的矩阵格式显示。

2X2 只是这个程序中的一个例子,二维数组必须大于或等于 50。

            else
           {
            int[][] array; 
           //this will hold the multiplied thing

            array=multiply(matrix,matrix2);

            System.out.println("this is the result of the multiplication");
            //print out the array
            for(int i=0; i<row; i++)
            {
                for( int j=0; j< col2; j++)
                {
                    System.out.print(array[i][j] + " \t");

                }
            }   

【问题讨论】:

    标签: java arrays matrix


    【解决方案1】:

    这应该可以,但是以漂亮的方式进行格式化并不那么容易。

    for(int i=0; i<row; i++) {
    
            for( int j=0; j< col2; j++) {
    
                System.out.print(array[i][j] + " \t");
            }
            System.out.println();
    } 
    

    【讨论】:

    • 我认为这只有在数字很短的情况下才有效,如果一个数字超过制表符行而下一行中的数字没有,它会奇怪地移动一行。跨度>
    • 这就是我所说的“以漂亮的方式格式化”的意思。他很快就会发现它:P
    【解决方案2】:

    在您的代码中添加一行:

    System.out.println("this is the result of the multiplication");
            //print out the array
            for(int i=0; i<row; i++)
            {
                for( int j=0; j< col2; j++)
                {
                    System.out.print(array[i][j] + " \t");
    
                }
                System.out.println();
            }  
    

    【讨论】:

      【解决方案3】:

      或制作这样的方法

        public static void printMatrix(int[][] mat) {
        System.out.println("Matrix["+mat.length+"]["+mat[0].length+"]");
             int rows = mat.length;
             int columns = mat[0].length;
             for (int i = 0; i < rows; i++) {
                 for (int j = 0; j < columns; j++) {
                     System.out.printf("%4d " , mat[i][j]);
                 }
                 System.out.println();
             }
             System.out.println();
        }
      

      并从你的主程序中调用它

      printMatrix(array);
      

      【讨论】:

        猜你喜欢
        • 2023-04-08
        • 2012-10-01
        • 1970-01-01
        • 2011-07-01
        • 2021-04-06
        • 2022-01-03
        • 1970-01-01
        • 2020-06-12
        • 2016-09-03
        相关资源
        最近更新 更多