Zeyad
Zeyad

Reputation: 13

Why does this code in java print a reference instead the result of invoking the method?

I am supposed to write a method that accepts 3 2-D arrays of This method should determine whether one of the matrices is the result of matrix addition of the other two.

public class Matrix {
    public static void main(String[]args){
        int [][] a = {{5,2,3},{4,1,6},{0,7,2}};
        int [][] b = {{1,2,3},{4,5,6},{0,1,2}};
        int [][] t = {{6,4,6},{8,6,12},{0,8,4}};
        System.out.println(add(a,b));
        System.out.println(check(a,b,t));
    }

    public static int [][] add(int[][]a,int[][]b){
        int i=0;
        int j=0;
        int[][] r = new int [3][3];
        while (i<a.length){
            r[i][j] = a[i][j] + b[i][j];
                i++;
                j++;
        }
        return r;
    }
    public static boolean check(int[][]a,int[][]b,int[][]t){
        int i = 0;
        int j = 0;
        while(i<t.length){
            if(t==add(a,b))
                return true;
        }
        return false;
    }
}

Upvotes: 1

Views: 641

Answers (1)

Mureinik
Mureinik

Reputation: 312116

add returns an array. Arrays in Java are objects, but they do not override the toString() method. When printing, you'd print their default toString() call, which is implemented by Object as return getClass().getName() + "@" + Integer.toHexString(hashCode());.

Luckily, Java provides a utility in the form of java.util.Arrays.deepToString(Ojbect[]) to generate a more readable string output:

System.out.println(Arrays.deepToString(add(a,b)));

EDIT:
Your add method is also wrong. Your code iterates i and j together, so it only sums the elements along the matrix's diagonal instead of adding all of them. You should use a nested loop instead:

public static int [][] add(int[][]a, int[][]b) {
    int[][] r = new int [3][3];
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            r[i][j] = a[i][j] + b[i][j];
        }
    }
    return r;
}

Your check method, by the way, is also wrong - it attempts to compare the array itself instead of is elements:

public static boolean check(int[][]a, int[][]b, int[][]t) {
    int[][] r = add(a, b);
    for (int i = 0; i < 3; ++i) {
        for (int j = 0; j < 3; ++j) {
            if (r[i][j] != t[i][j]) {
                return false;
            }
        }
    }

    return true;
}

Upvotes: 1

Related Questions