简体   繁体   English

我在Java中遇到了指针问题。 如何修复java.lang.NullPointerException?

[英]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. 这是从Java的稀疏矩阵中获取元素的方法。 I keep getting a java.lang.NullPointerException error. 我不断收到java.lang.NullPointerException错误。 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() . 在while循环中使用.getColumn()并调用.getColumn().getNextColumn()后,请检查matrixentry是否为null

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. 我建议您对代码运行Findbugs It does an amazing job catching lots of little things, for example the null check on matrixentry after you've already accessed it. 它捕获了许多小东西,做得非常好,例如,访问完矩阵后对null进行空检查。

Are your rowAarray and colArray properly initialized? 您的rowAarray和colArray是否正确初始化?
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. 您在对象上调用method,然后仅将其检查为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 . 基本的Sun Java Arrays教程对此进行了介绍 You could eventually use Arrays#fill() for that. 您最终可以使用Arrays#fill()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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