有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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(" ");
    }      
 }

共 (4) 个答案

  1. # 1 楼答案

    public static double[][] multiplyMatrix(double[][] A, double[][] B)。 这里返回一个双数组。这不是一种原始类型。因此,将使用数组的defaulttoString()方法(它打印classname@hashCode,从而输出)。必须使用Arrays.toString()正确打印值

  2. # 2 楼答案

    #deepToString Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings.

    多维数组应该使用java.util.Arrays.deepToString(array)。当前正在打印Object引用的String表示


    可以使用#replace方法将[]替换为{}

    //...
    public static void main(String[] argss){
        // TEST multiplyMatrix      
        System.out.println(" ---- Test Multiply Matrix ---- ");
        double array[][] = multiplyMatrix(A,B);
        String finalString = Arrays.deepToString(array)
                                   .replace("[", "{")
                                   .replace("]", "}");
        System.out.println(finalString);
        }//...
    
  3. # 3 楼答案

    您可能需要使用数组。来自java的toString。util。数组来打印数组

    或者,如果希望输出更加自定义,可以对数组进行迭代

  4. # 4 楼答案

    [[D@7f31245a表示Double的2D数组,后跟实际对象的哈希代码

    您的multiplyMatrix()方法返回的正是这个,但调用的toString()方法是Object上的方法,它正好打印这个。您需要使用Arrays类上的方法来预打印数组

    干杯