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