2012-02-01 41 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:空對象的方法。 希望它可以幫助你。

相關問題