views:

113

answers:

4

This is a method that gets a element from a Sparse Matrix in java. I keep getting a java.lang.NullPointerException error. I have looked over the code and can't find the error.

public int getElement(int row,int col){
    int result = 0;
    MatrixEntry matrixentry = null;
    if ((row >= 0) && (row < getNumRows()) &&
        (col >= 0) && (col < getNumCols())) {
         if (col == colArray[col].getColumn() &&  row ==rowArray[row].getRow()){
        matrixentry = rowArray[row];
        while (matrixentry.getColumn() < col) {
                 matrixentry = matrixentry.getNextColumn();
        } // end while
                 if (matrixentry.getColumn() > col){
                     return 0;
                 }
                 if (matrixentry == null){
                     return 0;
                 }// 
             result = matrixentry.getData();

         }// 

    }// 
    return result;

} // end
A: 

Are your rowAarray and colArray properly initialized?
According to your comment they are not.

Your code is hard to read and there are inconsistent checks like this

if (matrixentry.getColumn() > col) { 
    return 0;
}
if (matrixentry == null){ 
    return 0;
}

You call method on the object and only then check it for null.

If your are going to bind your life with the programming and it is not just a HomeWork I would recommend to you to treat your code presentation and expressiveness as your visit card.

Mykola Golubyev
private MatrixEntry[] rowArray = new MatrixEntry[0];private MatrixEntry[] colArray = new MatrixEntry[0]; here is my initialized rowArray and colArray
Ben Fossen
But those are zero length arrays. How do you plan to add elements to those?
duffymo
A: 

You need to preinitialize the array elements. That's covered by the basic Sun Java Arrays tutorial. You could eventually use Arrays#fill() for that.

BalusC
+1  A: 

You check matrixentry for null after you already used it in the while loop and to call .getColumn() and .getNextColumn().

I guess your code would do better if you checked first:

    matrixentry = rowArray[row];

    while (null != maxtrixentry && matrixentry.getColumn() < col) {
         matrixentry = matrixentry.getNextColumn();
    }

    if (null == maxtrixentry || matrixentry.getColumn() > col){
        return 0;
    }
    result = matrixentry.getData();
rsp
There are cases when you have to check object for null. But not that one. You are the one who creates rowArray. How can it contains null objects?
Mykola Golubyev
The original code expects to see null objects after the loop: `if (matrixentry == null) { return 0; }` so it should check inside the loop too. Btw, who knows what gets returned from `.getNextColumn()` ? That's not part of the array per se.
rsp
+1  A: 

I recommend that you run Findbugs on your code as well. It does an amazing job catching lots of little things, for example the null check on matrixentry after you've already accessed it.

Jay R.