Java 如何修复此ArrayIndexOutOfBoundsException
谁能给我解释一下为什么我在这里得到ArrayIndexOutboundsException? 这是我的错误:Java 如何修复此ArrayIndexOutOfBoundsException,java,Java,谁能给我解释一下为什么我在这里得到ArrayIndexOutboundsException? 这是我的错误: public int get(int r, int c) { return matrix[r][c]; } 我创建了一个tester类,并按如下方式调用get方法: java.lang.ArrayIndexOutOfBoundsException: 0 at Matrix.get(Matrix.java:117) at MatrixTest.dispa
public int get(int r, int c)
{
return matrix[r][c];
}
我创建了一个tester类,并按如下方式调用get方法:
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)
在此之后:
case 5:
System.out.println(matrix.get(0, 0));
break;
int[]n=新的int[r][c];
对于(int i=0;i这里没有什么可讨论的,但是您是否考虑了这样一个事实:如果您声明一个新的int[3],数组中的第一个位置是[0],最后一个位置是[2]
为什么不在引发异常的行之前输出r和c的值呢?堆栈跟踪显示导致异常的越界索引为0,因此这意味着您已经在某处创建了一个零长度数组。我不知道您发布的代码的位置,但可能在以下语句中:
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;
r
或c
都是0。你从哪里得到异常?你能告诉我们堆栈跟踪吗?你能告诉我们调用get方法的代码以及你是如何创建矩阵实例的吗?看起来你可能只是使用了一个大于数组大小的数字,或者r
或c
步数你的数组。我们不知道哪个(可能两者都是),但我认为检查边界没有任何害处。堆栈跟踪显示越界索引为0,因此看起来你在某处创建了一个零长度数组。不幸的是,第117行也是一个越界索引,因为你在Matrix.java中只发布了28行代码:)可能在最后一段代码中,你说newint[r][c]
,或者r
或者c
是0?@ajb我会把它作为一个答案发布(我本来打算,但后来我看到了你的评论,所以我会让你这么做)。
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;
int[][] n = new int[r][c];