0
public class MatrixAddition {

    public static void main(String[] args) {

        int ar1[][] = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } };
        int ar2[][] = { { 8, 7, 6 }, { 5, 4, 3 }, { 2, 1, 0 } };

        addArray(ar1, ar2);

    }

    private static void addArray(int[][] tmp1, int[][] tmp2) {
        int[][] sum = {};
        System.out.println(" ");
        System.out.println("The sum of the two matrices is");
        for (int i = 0; i < 3; i++) {
            for (int j = 0; j < 3; j++) {
                sum[i][j] = tmp1[i][j] + tmp2[i][j];
                System.out.print(sum[i][j] + "  ");
            }

        }

    }

}

output:

The sum of the two matrices is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
1
  • 4
    What do you think int[][] sum = {}; does? Commented Dec 28, 2014 at 19:22

2 Answers 2

6

Your only problem is that you don't initialize the sum array properly :

int[][] sum = new int[tmp1.length][tmp1[0].length];

You initialize it to an empty array.

Sign up to request clarification or add additional context in comments.

Comments

0

I don't think you need a sum array, and if you did you would have to size it based on the input arrays.

private static void addArray(int[][] tmp1, int[][] tmp2) {
    System.out.println(" ");
    System.out.println("The sum of the two matrices is");
    for (int i = 0; i < tmp1.length; i++) {
        for (int j = 0; j < tmp1[i].length; j++) {
            if (j != 0) {
                System.out.print(", ");
            }
            int sum = tmp1[i][j] + tmp2[i][j];
            System.out.print(sum);
        }
        System.out.println();
    }
}

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.