我不得不为学校编写这个程序来增加一对二维数组。我不停地越界:当我尝试运行程序时出现3错误。
我已经多次查看过这段代码,并且不能为我的生活找出故障发生的地方。我运行了一个调试,第一个断点位于if语句“if(a [0] .length!= b.length)”我无法弄清楚为什么这是一个断点。
有人可以帮助我吗?
public class Multiply {
public static double[][] Multiply_2D_Arrays(double[][] a, double[][] b)
{
if (a[0].length != b.length) // Check to see if the number of a's colums equals the number of b's rows
{
throw new IllegalArgumentException("Matrices don't match: " + a[0].length + " != " + b.length);
}
int a_rows = a.length; // Defines the variable M as the row length of array a
int b_columns = b[0].length; // Defines the variable N as the column length of array b
double[][] c = new double[a_rows][b_columns]; // This means that the dimensions of array c will be the rows of a by the columns of b
for(int i = 0; i < a.length; i++)
{
for(int j = 0; j < b[0].length; j++)
{
for(int k = 0; k < a[0].length; )
{
c[i][j] += a[i][k] * b[k][j]; //Iterates through each row and column of array a and b and then adding it to the dot point sum
}
}
}
return c; //returns the final new array c
}
public static void main(String[] args)
{
double[][] array1 = {{4.0, 5.0, 6.0}, {2.0, 1.0, 4.0}, {8.0, 7.0, 6.0}, {1.0, 1.0, 2.0}};
double[][] array2 = {{5.0, 7.0, 7.0, 8.0}, {8.0, 8.0, 9.0, 2.0}, {10.0, 2.0, 3.0, 1.0}};
double[][] array3 = Multiply.Multiply_2D_Arrays(array1, array2); //Calls the Multiply_2D_Arrays method
for(int i = 0; i < array3.length; i++)
{
for (int j = 0; j < array3.length; j++)
{
System.out.print(array3[i][j] + " ");
}
}
System.out.println();
}
}
答案 0 :(得分:1)
你错过了k++
for(int k = 0; k < a[0].length; )
然后你有一个无限循环
此外,如果您想将结果打印为矩阵,请将System.out.println()
放入for循环:
for(int i = 0; i < array3.length; i++)
{
for (int j = 0; j < array3.length; j++)
{
System.out.print(array3[i][j] + " ");
}
System.out.println();
}
答案 1 :(得分:0)
如果您将此for(int k = 0; k < a[0].length; )
更改为for(int k = 0; k < a[0].length;k++ )
错过k++
内圈for循环,程序将正确执行。