2012-02-01 76 views
0

我有得到回报型传感器 在大胆的方法是在那里我得到一个NullPointerException异常运行时,不明白为什么。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; 
     } 
+1

因为有些东西是'null'。但是不可能说出什么,因为你没有向我们展示过如何声明's1',初始化等。 – 2012-02-01 00:14:17

+0

s1 [i]为空。找出为什么它不是在你期望的地方创造的。 – 2012-02-01 00:14:29

回答

6

你不告诉我们在哪儿创建s1,但它看起来像s1没有了什么东西对一些指标i

我倾向于写我像这样的循环,使这样的代码有点清洁

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; 

事情是这样的格式非常重要,将有助于你避免在首位的错误,使他们更容易找到当他们有这样的事情....

+0

想通了,谢谢! – Mjall2 2012-02-01 00:16:40

+0

@ Mjall2,多数民众赞成,但你应该处理你的代码的格式和清晰度... – hvgotcodes 2012-02-01 00:24:35

1

一些在阵列S1的元素是空的,当你试图调用你得到NPE:空对象的方法。 希望它可以帮助你。