public class Matrix
{
private int[][] matrix;
private int rows;
private int cols;
public Matrix(int r, int c)
{
matrix = new int[r][c];
this.rows = r;
this.cols = c;
}
public Matrix(int[][] m)
{
matrix = new int[m.length][m[0].length];
this.rows = m.length;
this.cols = m[0].length;
for(int i=0; i<m.length; i++)
{
for(int j=0; j<m[0].length; j++)
{
matrix[i][j] = m[i][j];
}
}
}
This is how I started my class with my constructors and later on I included the code:
public int get(int r, int c)
{
return matrix[r][c];
}
Can anyone please explain to me why I am getting the ArrayIndexOutOfBoundsException here? This was my error:
java.lang.ArrayIndexOutOfBoundsException: 0
at Matrix.get(Matrix.java:117)
at MatrixTest.dispatch(MatrixTest.java:76)
at MatrixTest.main(MatrixTest.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
I made a tester class and called the get method like this:
case 5:
System.out.println(matrix.get(0, 0));
break;
After this:
int[][] n = new int[r][c];
for(int i=0; i<n.length; i++)
{
for(int j=0; j<n[0].length; j++)
{
n[i][j] = scan.nextInt();
}
}
Matrix matrix = new Matrix(n);
break;