Java程序输出奇怪的结果
我的java代码有输出问题。 我正在尝试实现这个乘法矩阵方法,它编译得很好。唯一的问题是我的输出。我似乎得到了以下信息:
---- Test Multiply Matrix ----
[[D@7f31245a
Should return C={{ 3, 2},{ 1, 1}}
有人能帮我理解我哪里出了问题吗。谢谢 以下是我的源代码:
public class Recommendation
{
public static double[][] multiplyMatrix(double[][] A, double[][] B)
{
int aRows = A.length;
int bRows = B.length;
int aColumns = A[0].length;
int bColumns = B[0].length;
if((aColumns != bRows))
{
return null;
}
else
{
double[][] C = new double[aRows][bColumns];
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
C[i][j] = 0;
}
}
for (int i = 0; i < aRows; i++)
{
for (int j = 0; j < bColumns; j++)
{
for (int k = 0; k < aColumns; k++)
{
C[i][j] += A[i][k] * B[k][j];
}
}
}
return C;
}
}
static double [][] A = {{ 1, 0, 2},
{ 0, 1, 1}};
static double [][] B = {{1, 2},
{ 0, 1},
{ 1, 0}};
public static void main(String[] argss)
{
// TEST multiplyMatrix
System.out.println(" ---- Test Multiply Matrix ---- ");
System.out.println(multiplyMatrix(A,B)); // should return C={{ 3, 2},{ 1, 1}}
System.out.println("Should return C={{ 3, 2},{ 1, 1}}");
System.out.println(" ");
}
}
# 1 楼答案
public static double[][] multiplyMatrix(double[][] A, double[][] B)
。 这里返回一个双数组。这不是一种原始类型。因此,将使用数组的defaulttoString()方法(它打印classname@hashCode
,从而输出)。必须使用Arrays.toString()
正确打印值# 2 楼答案
多维数组应该使用
java.util.Arrays.deepToString(array)
。当前正在打印Object
引用的String
表示可以使用
#replace
方法将[]
替换为{}
# 3 楼答案
您可能需要使用数组。来自java的toString。util。数组来打印数组
或者,如果希望输出更加自定义,可以对数组进行迭代
# 4 楼答案
[[D@7f31245a
表示Double
的2D数组,后跟实际对象的哈希代码您的
multiplyMatrix()
方法返回的正是这个,但调用的toString()
方法是Object
上的方法,它正好打印这个。您需要使用Arrays
类上的方法来预打印数组干杯