简体   繁体   中英

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.

 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 .

I tend to write my for loops like so to make code like this a bit cleaner

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. Hope it helps you.

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