2013-12-18 51 views
1
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; 
+1

*如果*你得到的例外呢?你能告诉我们堆栈跟踪吗? – user2357112

+0

您可以显示调用get方法的代码以及如何创建Matrix实例?似乎你可能只是使用比数组大小更大的数字 –

+0

“r”或“c”退出阵列。我们不知道哪个(可能是两者),但我没有看到任何损害检查边界。 – Makoto

回答

0

很少有去在这里,但你是否考虑到如果你声明一个新的int [3]数组中的第一个位置是[0],最后一个是[2]的事实?

为什么不在输出异常的行之前输出r和c的值?

0

堆栈跟踪表示导致异常的出界索引是0,所以这意味着你已经在某处创建了一个长度为零的数组。我不能告诉你,从发布的代码在那里,但可能在此声明:

int[][] n = new int[r][c]; 

要么rc为0

相关问题