使用二维数组来表示矩阵。计算矩阵的乘积,并将数据存储在新的二维数组中。打印矩阵A第2行与矩阵B第1列的乘积。您想要将A和B相乘,得到乘积矩阵C。为简便起见,假设(现在)您只想计算乘积矩阵C中第2行、第1列的值。但是,要计算矩阵C的row2第1列的值,您需要计算A的整个第2行和B的整个第1列的“点积”:
我的程序告诉我,我的数组索引是越界的异常为4,但我不确定如何解决它
public class lab
{
public static void main(String[] args)
{
int[][] A = { {10,55,4,89,39} , {45,9,49,98,23} , {4,8,90,23,9}
{8,32,80,2,31} };
int[][] B = { {10,55,4,89,39} , {45,9,49,98,23} , {4,8,90,23,9} , {8,32,80,2,31} };
int[][] C = new int[A.length][B[0].length];
int sum = 0;
for (int i = 0 ; i < 5 ; i++)
{
sum = sum + A[2][i]*B[i][1];
}
C[2][1] = sum;
System.out.println(sum);
} // end main
} // end class输出应为:
1616
发布于 2017-10-31 12:12:31
你的数组A和B都有4个元素,你正在运行循环到5。你需要像下面这样改变for循环。
for (int i = 0 ; i < 4 ; i++)发布于 2017-10-31 12:21:39
对于阵列B,您可以t get element of B[4][4]. Maximum will be B[3][4]. array indexes starts from 0. so you have elements. 0,1,2,3. when counter hits 4, you try to get the element B[4] and the index doesnt exist。这就是你得到这个错误的原因。检查附加的图像也。

检查下图
https://stackoverflow.com/questions/47027726
复制相似问题