初学者在这里,我需要帮助解决这个异常超出范围的错误。我真的被困了! 试图乘以矩阵。请帮忙
package arrayPractice1;
import java.util.Arrays;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Type how much rows will matrix A have");
int rowA = in.nextInt();
System.out.println("Type how much columns will matrix A have");
int colA = in.nextInt();
System.out.println("Type how much rows will matrix B have");
int rowB = in.nextInt();
System.out.println("Type how much columns will matrix B have");
int colB = in.nextInt();
int[][] matrixA = new int[rowA][colA];
int[][] matrixB = new int[rowB][colB];
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[i].length; j++) {
System.out.println("Enter value for row " + i + " and column " + j);
matrixA[i][j] = in.nextInt();
}
}
for (int i = 0; i < matrixB.length; i++) {
for (int j = 0; j < matrixB[i].length; j++) {
System.out.println("Enter value for row " + i + " and column " + j);
matrixB[i][j] = in.nextInt();
}
}
in.close();
int[][] multiply = new int[colA][rowB];
int sum = 0;
System.out.println("Mult. of matrixA and matrixB");
for (int i = 0; i < rowA; i++) {
for (int j = 0; i < colB; j++) {
for (int k = 0; k < rowA; k++) {
sum = sum + matrixA[i][k] * matrixB[k][j];
}
multiply[i][j] = sum;
sum = 0;
}
}
System.out.println(Arrays.deepToString(multiply));
}
}
答案 0 :(得分:0)
for (int i = 0; i < rowA; i++) {
for (int j = 0; i < collB; j++) {
for (int k = 0; k < rowA; k++) {
sum = sum + matrixA[i][k] * matrixB[k][j];
}
multiply[i][j] = sum;
sum = 0;
}
}
这里你要检查我是否小于collB,而这是真的你使j大于矩阵[k] [j]允许导致索引超出界限错误。