我该如何打印出这个矩阵?[复制]

How would I print out this matrix? [duplicate]

提问人:Ethan Do 提问时间:11/13/2023 更新时间:11/13/2023 访问量:38

问:

我有这个代码:

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;

这在运行器文件中:

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 的文本(我忘记了它们叫什么)。

Java 多维数组

评论

0赞 Gyro Gearloose 11/13/2023
好吧,你看到的是对象,而不是内容。你的代码中已经有一个嵌套的for循环,只需继续,让它按照你喜欢的格式打印出你的矩阵。

答:

0赞 Sash Sinha 11/13/2023 #1

使用数组。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]]