简体   繁体   English

方法中的NullPointerException

[英]NullPointerException in method

I have a method that gets returns a type SENSOR In the bold is where I am getting a runtime NullPointerException, cannot understand why. 我有一个获取返回类型为SENSOR的方法。粗体是我获取运行时NullPointerException的地方,无法理解原因。

 public Sensor getSensorAt(int x,int y,GridMap grid)
      {
       /*go through sensor storage array 
       * for eachsensor index call the get x get y method for that 
       * compare it to the x,y of the robot 
       * 
       */  

        for(int i=0;i<s1.length;i++){ 
             if(s1[i].getX() == x){    <======= NullpointerException
            if(s1[i].getY()== y){ 

            return s1[i]; 
            } 
          }      
        } 
        return null;
      }

You did not show us where s1 is created, but it looks like s1 does not have anything in it for some index i . 您没有向我们展示s1的创建位置,但是对于某些索引i来说s1似乎没有任何内容。

I tend to write my for loops like so to make code like this a bit cleaner 我倾向于像这样编写我的for循环,以使这样的代码更简洁

Object result = null;
for(int i=0;i<s1.length;i++){ 
    Object current = s1[i]; // Replace Object with whatever your array actually contains
    if(current.getX() == x && current.getY() == y) {
        result = current;
        break; // if you only need the first match
    }
}

return result;

Things like formatting are important and will help you prevent bugs in the first place, and make them easier to find when they do happen.... 诸如格式化之类的东西很重要,它将首先帮助您防止错误,并使它们在发生时更容易找到。

Some of the elements in the array s1 is null, and when you are trying to invoke a method on that null object you are getting NPE. 数组s1中的某些元素为null,并且当您尝试在该null对象上调用方法时,您将获得NPE。 Hope it helps you. 希望对您有帮助。

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

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