[英]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.