[英]NullPointerException in method
我有一個獲取返回類型為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;
}
您沒有向我們展示s1
的創建位置,但是對於某些索引i
來說s1
似乎沒有任何內容。
我傾向於像這樣編寫我的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;
諸如格式化之類的東西很重要,它將首先幫助您防止錯誤,並使它們在發生時更容易找到。
數組s1中的某些元素為null,並且當您嘗試在該null對象上調用方法時,您將獲得NPE。 希望對您有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.