Mja*_*ll2 0 java null pointers exception
我有一个方法,返回一个类型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;
}
Run Code Online (Sandbox Code Playgroud)
你没有告诉我们在哪里s1创建,但看起来s1它没有任何东西用于某些索引i.
我倾向于编写我的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;
Run Code Online (Sandbox Code Playgroud)
像格式化这样的东西很重要,它可以帮助你首先防止错误,并在发生错误时更容易找到错误....
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |