代码之家  ›  专栏  ›  技术社区  ›  Ethan Do

我该如何打印出这个矩阵?[副本]

  •  0
  • Ethan Do  · 技术社区  · 1 年前

    我有这个代码:

    public static int[][] doubleMat(int[][] mat) 
    {
        int row = mat.length;
        int col = mat[0].length;
        int[][] num = new int[row][col];
    
        for (int x = 0; x < row; x++) 
        {
            for (int y = 0; y < col; y++) 
            {
                num[x][y] = mat[x][y] * 2;
            }
        }
        return num;
    

    在runner文件中:

    int[][] mat = {{45,101,87,12,41,0},{12,8,12,8,15,841},{-12,-1,-741,-1,0,74}};
    System.out.println(Array2DHelper2.doubleMat(mat));
    

    它不断返回[[I@4617c264,而不是2D数组。我很确定这与toString有关,但我不确定如何执行。我还必须将其打印为整个数组,而不是打印出每个单独的点。

    我试过使用Arrays.toString(Array2DHelper2.doublemat(mat))打印它,我认为这会奏效,但它打印的文本更多类似于[[I@4617c264(我忘了它们叫什么了)。

    1 回复  |  直到 1 年前
        1
  •  0
  •   Sash Sinha    1 年前

    使用 Arrays. deepToString() 用于打印多维数组:

    import java.util.Arrays;
    
    class Main {
      public static int[][] doubleMat(int[][] mat) {
        int row = mat.length;
        int col = mat[0].length;
        int[][] num = new int[row][col];
        for (int x = 0; x < row; x++) {
          for (int y = 0; y < col; y++) {
            num[x][y] = mat[x][y] * 2;
          }
        }
        return num;
      }
    
      public static void main(String[] args) {
        int[][] mat = { { 45, 101, 87, 12, 41, 0 }, { 12, 8, 12, 8, 15, 841 }, { -12, -1, -741, -1, 0, 74 } };
        System.out.printf("Before doubleMat: %s%n", Arrays.deepToString(mat));
        System.out.printf("After doubleMat: %s%n", Arrays.deepToString(doubleMat(mat)));
      }
    }
    

    输出:

    Before doubleMat: [[45, 101, 87, 12, 41, 0], [12, 8, 12, 8, 15, 841], [-12, -1, -741, -1, 0, 74]]
    After doubleMat: [[90, 202, 174, 24, 82, 0], [24, 16, 24, 16, 30, 1682], [-24, -2, -1482, -2, 0, 148]]