Peter Downey
Peter Downey

Reputation: 21

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; null when I try to input anything into it. 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

Upvotes: 1

Views: 58

Answers (1)

GhostCat
GhostCat

Reputation: 140457

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. And of course a should have the same number of columns as b, too. 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!

You see, in Java, a two-dim array is nothing but an array that contains another array. Your initial code would only initiate that "outer" array, leaving the "inner" arrays at null.

Upvotes: 2

Related Questions