Reputation: 1038
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?
Upvotes: 1
Views: 620
Reputation: 19189
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.
Upvotes: 5