简体   繁体   中英

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 

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM