Mjall2
Mjall2

Reputation: 263

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;
      }

Upvotes: 0

Views: 83

Answers (2)

hvgotcodes
hvgotcodes

Reputation: 120168

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....

Upvotes: 6

Sajan Chandran
Sajan Chandran

Reputation: 11487

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.

Upvotes: 1

Related Questions