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];
}
}
}
这是我开始了我的班级我的构造函数,稍后我包括代码:为什么我在这里得到ArrayIndexOutOfBoundsException异常我怎样才能解决这个ArrayIndexOutOfBoundsException异常
public int get(int r, int c)
{
return matrix[r][c];
}
谁能请给我解释一下? 这是我的错误:
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)
我做了一个测试类和一个名为get方法是这样的:
case 5:
System.out.println(matrix.get(0, 0));
break;
在此之后:
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;
*如果*你得到的例外呢?你能告诉我们堆栈跟踪吗? – user2357112
您可以显示调用get方法的代码以及如何创建Matrix实例?似乎你可能只是使用比数组大小更大的数字 –
“r”或“c”退出阵列。我们不知道哪个(可能是两者),但我没有看到任何损害检查边界。 – Makoto