Search code examples
javapointersmatrixsparse-matrix

I am having a problem with pointers in java. How do I fix a java.lang.NullPointerException?


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 

Solution

  • 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();