简体   繁体   中英

Add two matrices in Java

I'm trying to add two matrices and I get and exception when the compiler attempts to call the sum method.

public static void main(String[] args) {

    int[][] a = new int[3][3];
    int[][] b = new int[3][3];

    for (int i = 0; i < a.length; i++)
    {
        for (int j = 0; j < a[0].length; j++)
        {
            a[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Enter a[" + i + "][" + j + "]"));
        }
    }
    for (int i = 0; i < b.length; i++)
    {
        for (int j = 0; j < b[0].length; j++)
        {
            b[i][j] = Integer.parseInt(JOptionPane.showInputDialog("Enter b[" + i + "][" + j + "]"));
        }
    }

I get the exception at the next line.

    int[][] c = sum(a,b);

    for (int[] row: c)
    {
        for (int e: row)
        {
            System.out.print(e + "\t");
        }
    }

}
public static int[][] sum(int[][] a, int[][] b)
{
    int[][] c = new int[a.length][a[0].length];

    for (int i = 0; i < a.length; i++)
    {
        for (int j = 0; i < a[i].length; j++)
            c[i][j] = a[i][j] + b[i][j];
    }
    return c;
}

Anybody can help me with that?

You have a typo in your inner loop:

for (int j = 0; i < a[i].length; j++)

should be

for (int j = 0; j < a[i].length; j++)

and causes an ArrayIndexOutOfBoundsException since j goes beyond the size of the array.

When an exception occurs, the first thing you look at is the name of the exception. It's often very informative. In this case it tells us that we accidentally looped too far. If the name isn't informative, we can at least find out where the error occurred. The stack trace contains the line at which the error occurred. If none of those things helps/exists, we can use a debugger, or print debug messages along the way, to diagnose the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM