java - 矩阵乘法中的越界异常
问题描述
我写了这段代码。
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Please enter the rows \"then\" columns of the first array: ");
int a = console.nextInt();
int b = console.nextInt();
int[][] arr1 = new int[a][b];
System.out.println("Please enter the rows \"then\" columns of the second array: ");
int c = console.nextInt();
int d = console.nextInt();
int[][] arr2 = new int[c][d];
if (b != c) {
System.out.println("these two matrices can't be multiplied!!");
} else {
int[][] mult = new int[a][c];
System.out.println("Please enter the elements of the first array : ");
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
arr1[i][j] = console.nextInt();
}
}
System.out.println("Please enter the elements of the second array : ");
for (int i = 0; i < c; i++) {
for (int j = 0; j < d; j++) {
arr2[i][j] = console.nextInt();
}
}
int sum = 0;
for (int i = 0; i < a; i++) {
for (int j = 0; j < d; j++) {
for (int k = 0; k < c; k++) {
sum += arr1[i][k] * arr2[k][j];
mult[i][j] = sum;
}
sum = 0;
}
}
for(int i=0;i<a;i++){
for(int j=0;j<d;j++) {
System.out.print(mult[i][j] + " ");
}
System.out.println("");
}
}
}
}
当我运行它时,它说java.lang.ArrayIndexOutOfBoundsException
.
不知道为什么,谢谢帮忙。
解决方案
据我所知,这可能是问题所在:int[][] mult = new int[a][c]
,应该是new int[a][d]
P / s:如果您可以格式化代码的第一部分会更好
推荐阅读
- java - 带有 Unity3D 前台服务的 Android 插件
- excel - 具有最大值的excel索引函数
- postgresql - postgresql UPDATE中的运行计数
- azure - 是否可以使用 Azure Active Directory B2C 来保护非 B2C 目录中包含的 API?
- excel - 在子文件夹的指定单元格中添加超链接
- react-native - React Native - 通过转换增加/减少点击时的视图高度
- continuous-integration - GitLab CI 不起作用:缺少自定义执行程序 RunExec
- html - 每页的垫子分页器项目在角度 9 中不起作用
- bash - 在 bash shell 中,将标准错误重定向到标准输出并使用字符串前缀引用错误部分
- sql - 使用 APEX_JSON 生成 JSON 文档