【问题标题】:JAVA printing correct output with an error [[I@6acbcfc0 in MATRIX-ADDITION [duplicate]JAVA 打印正确的输出并出现错误 [[I@6acbcfc0 in MATRIX-ADDITION [重复]
【发布时间】:2020-09-22 12:16:50
【问题描述】:

我在二维数组的帮助下编写了添加两个矩阵的代码。但运行后,它显示错误[[I@6acbcfc0 的结果。如果您知道[[I@6acbcfc0 的含义,请您也描述一下。以下是代码:

public static void main(String[] args) {
    
    Scanner sc = new Scanner (System.in);
    
    System.out.println("Enter dimensions: ");       
    int rows = sc.nextInt();
    int cols = sc.nextInt();
    
    int a[][] = new int [rows][cols];
    int b[][] = new int [rows][cols];
    
    System.out.println("Enter first matrix: ");     
    for (int i = 0; i<rows; i++) {
        for (int j = 0; j<cols; j++) {
            a[i][j] = sc.nextInt();
        }
    }
    
    System.out.println("Enter second matrix: ");        
    for (int i = 0; i<rows; i++) {
        for (int j = 0; j<cols; j++) {
            b[i][j] = sc.nextInt();
        }
    } 
    
    int c [][] = new int [rows][cols];
    
    for (int i = 0; i<rows; i++) {
        for (int j = 0; j<cols; j++) {
            c[i][j] = a[i][j] + b[i][j];
        }
    }
    
    System.out.println("Result is " + c);
    for(int i = 0; i<rows; i++) {
        for (int j = 0; j<cols; j++) {
            System.out.print(c[i][j] + " ");
        }
        System.out.println();
    }
}

}

输出是

Enter dimensions: 
2 2

Enter first matrix: 

1 2

1 2

Enter second matrix: 

1 2

1 2

Result is [[I@6acbcfc0

2 4 

2 4 

请帮助我删除“[[I@6acbcfc”,如果您在我的代码中发现任何错误,请更正它,以便我能更好地理解它。谢谢。

【问题讨论】:

标签: java arrays matrix


【解决方案1】:

您正在使用 System.out.println("Result is " + c); 打印 c,因此它被添加到输出中。只需将其删除即可。

你也可以试试这个来打印二维数组。

System.out.println(Arrays.deepToString(c));

用于打印普通数组

System.out.println(Arrays.toString(c));

【讨论】:

  • 加上附录,奇怪的是,他们使用正确的方法来打印正下方的数组内容。
  • 是的,这有多奇怪。
【解决方案2】:

你的问题是你正在执行

 System.out.println("Result is " + c);

其中 c 是 int [][]

大概您希望由此打印出整个数组,但这并不是实际存在的行为。

您看到的打印结果是c.toString() 的结果,它没有被定义为对您有用的任何东西。

如果您想打印出数组内容,您必须编写代码以逐个元素地打印它。事实上,您已经完成了,就在下面。

for(int i = 0; i<rows; i++) {
    for (int j = 0; j<cols; j++) {
        System.out.print(c[i][j] + " ");
    }
    System.out.println();
}

所以只需从前面的println 调用中删除+ c

【讨论】:

    猜你喜欢
    • 2021-01-11
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多