我正在乘以Matrix1[10][2] * Matrix2[2][20]
,但每當我的類嘗試乘法時,總是會拋出與上述標題相同的異常。但是當我把行小於在矩陣1和列小於上矩陣兩行的列數,它執行沒有問題的矩陣乘法,這是我的乘法矩陣乘法中的java.lang.ArrayIndexOutOfBoundsException
public class MatrixCompute extends RecursiveAction
{
private CreateMatrix a,b;
private CreateMatrix c;
private int row;
MatrixCompute(CreateMatrix a , CreateMatrix b ,CreateMatrix c)
{
this(a , b ,c,-1);
}
MatrixCompute(CreateMatrix a, CreateMatrix b, CreateMatrix c, int row)
{
if (a.getCols() != b.getRow())
{
throw new IllegalArgumentException("rows/columns mismatch");
}
this.a = a;
this.b = b;
this.c = c;
this.row = row;
}
@Override
public void compute()
{
if (row == -1)
{
List<MatrixCompute> tasks = new ArrayList<>();
for (int row = 0; row < a.getRow(); row++)
{
tasks.add(new MatrixCompute(a, b, c, row));
}
invokeAll(tasks);
}
else
{
multiplyRowByColumn(a, b, c, row);
}
}
void multiplyRowByColumn(CreateMatrix a, CreateMatrix b, CreateMatrix c, int row) {
for (int j = 0; j < b.getCols(); j++) {
for (int k = 0; k < a.getCols(); k++) {
c.setValue(row, j, (int)(c.getValue(row, j) + a.getValue(row, k)* b.getValue(k, j)));
}
}
}
}
類和類包裹的基質:
public class CreateMatrix
{
private int[][] matrix;
public CreateMatrix (int row, int col)
{
matrix = new int[row][col];
}
public void fillMatrix()
{
for(int i = 0; i < matrix.length; i++)
{
for(int j = 0; j < matrix[i].length ;j++)
{
Random r = new Random();
matrix[i][j] = r.nextInt() * 5;
}
}
}
public int getCols()
{
return matrix[0].length;
}
public int getRow()
{
return matrix.length;
}
int getValue(int row, int col)
{
return matrix[row][col];
}
void setValue(int row, int col, int value)
{
matrix[row][col] = value;
}
}
這裏是正在執行該操作的statment:
result = new CreateMatrix(row, col);
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(new MatrixCompute(container[0], container[1], result));
和這裏的矩陣被decalred其中:
CreateMatrix matrix1 = new CreateMatrix(Integer.parseInt(txtfil.getText()), Integer.parseInt(txtcol.getText()));
container[0] = matrix1;
container[0].fillMatrix();
CreateMatrix matrix2 = new CreateMatrix(Integer.parseInt(txrow.getText()), Integer.parseInt(txtcol2.getText()));
container[1] = matrix2;
矩陣結果的最終大小由txrow.getText()
和txtcol.getText()
宣佈如此以來,在乘以矩陣必須是矩陣的列,唯一的例外之一必須是一樣矩陣2行,爲什麼在Matrix1的行和Matrix2的列中拋出我最大的值異常
你在MatrixCompute類的構造函數MatrixCompute(CreateMatrix a,CreateMatrix b,CreateMatrix c)中實際做了什麼? {(a,b,c,-1); } – xFighter
這只是一個開始迭代矩陣行的標誌,所以當行等於-1時,開始遍歷矩陣以獲取每個矩陣的行索引 –
Post exception。 – talex