0

Your have to add matrices. This does not work, and I'm not sure how to fix it! The two matrices I have inputed are shown below.

When I output the code, I get the location in the RAM instead of the added matrices.

I'm not sure where it went wrong! I would appreciate HELP! Thank you! :D

public static double[][] add(double[][] a1, double [][] a2)
{  
    for (int r = 0; r<a1.length; r++)
    {
        for (int c = 0; c<a1[r].length; c++)
        {
            a1[r][c] = a1[r][c] + a2[r][c];
        }

    }
    return a1;
}

public static void main(String[] args)
{
    double [][] arr = {{1,3,4},
                               {2,0,1}};

    double [][] arr1 = {{0,0,2},
                                 {5,6,7}};

    System.out.println(Matrix.add(arr, arr1));
}
0

2 Answers 2

3

You're calling println on an array, and you're seeing the toString() returned by an array. Don't do this. Either use Arrays.deepToString(...) or else use a for loop to iterate through the array printing out the results.

for example in pseudocode,

double[][] result = Matrix.add(...);
for go through rows
  for go through columns
    println the array item in the result array at row, column index
Sign up to request clarification or add additional context in comments.

4 Comments

Arrays.toString doesn't work. It gives the location in the RAM for arr and arr1.
Arrays.toString won't work for a double-indexed array. It will return a concatenation of each component's toString() result, which won't be any better than what OP is printing now.
@user2990722: see edit. Also there's the deepToString(...) method.
@TedHopp: you are right, but Arrays.deepToString(...) will work.
0

You're not printing it properly. Try this (tested and works):

public static double[][] add(double[][] a1, double [][] a2)
{  
    for (int r = 0; r<a1.length; r++)
    {
        for (int c = 0; c<a1[r].length; c++)
        {
            a1[r][c] = a1[r][c] + a2[r][c];
        }
    }
    return a1;
}

public static void main(String[] args) 
{
    double [][] arr1 = {{1,3,4},{2,0,1}};
    double [][] arr2 = {{0,0,2},{5,6,7}};
    double[][] sumMatrix = add(arr1,arr2);

    for (double r[] : sumMatrix)
    {
        for (double c : r)
            System.out.print(c + ", ");

        System.out.println("" + '\n');
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.