[英]Multiplying an array and a 2-d array in java
I'm trying to multiply an array and a 2d array on java and my program compiles but keeps returning the error java.lang.NullPointerException; 我试图在Java上乘以一个数组和一个2d数组,并且我的程序进行编译,但始终返回错误java.lang.NullPointerException; null when I try to input anything into it. 当我尝试向其中输入任何内容时为null。 Here is my code so far: 到目前为止,这是我的代码:
static double[][] productWithDiagonal(double[] a, double[][] b)
{
double[][] c = new double[3][];
{
for (int i = 0; i < b.length; ++i) {
for (int j = 0; j < b[1].length; ++j) {
c[i][j] = a[j] * b[i][j];
}
}
}
return c;
}
Thanks 谢谢
This here: 这里:
double[][] c = new double[3][];
Only instantiates your "rows". 仅实例化您的“行”。 You need something like 你需要类似的东西
double[][] c = new double[3][3];
Or more useful probably 或更有用的可能
... c = new double[b.length][b[0].length];
instead. 代替。 But just to be sure: those numbers there matter; 但是要确保:这些数字很重要; you should make sure that b for example is really a "regular rectangle" shaped matrix - so that all rows have the same number of columns. 您应该确保例如b确实是一个“规则矩形”形状的矩阵-以便所有行的列数均相同。 And of course a should have the same number of columns as b, too. 当然, a的列数也应该与b相同。 You could add such checks in the beginning of your method; 您可以在方法开始时添加此类检查; to ensure that the shapes of a and b actually allow for this multiplication! 确保a和b的形状实际上允许该乘法!
You see, in Java, a two-dim array is nothing but an array that contains another array. 您会看到,在Java中,二维数组只是一个包含另一个数组的数组。 Your initial code would only initiate that "outer" array, leaving the "inner" arrays at null . 您的初始代码只会启动该“外部”数组,而将“内部”数组保留为null 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.