我正在编写此代码,我正在调用一个方法来处理对象数组中的元素,为此,我首先需要检查元素是否为null。我正在使用if(array [x] [y]!= null),但我得到一个NPE指向这一行,我不明白为什么。
以下是相关代码:
检查方法:
$ch = curl_init();
$geoCodeUrl = 'https://maps.googleapis.com/maps/api/geocode/json?address=' . $zip . ',+United+States&key=' . $googleApiKey;
curl_setopt($ch,CURLOPT_URL, $geoCodeUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$result = curl_exec($ch);
curl_close($ch);
$GeoCode = json_decode($result);
$GeoLocator = new \stdClass();
if( isset($GeoCode->results[0]) ){
$GeoLocator->lat = $GeoCode->results[0]->geometry->location->lat;
$GeoLocator->lon = $GeoCode->results[0]->geometry->location->lng;
foreach($GeoCode->results[0]->address_components as $comp){
if( in_array('locality',$comp->types) ){
$GeoLocator->city = trim($comp->short_name);
}
else if( in_array('administrative_area_level_1',$comp->types) ){
$GeoLocator->state = strtoupper(trim(preg_replace('/\d/', '', $comp->short_name)));
}
}
}
else if( isset($GeoCode->results) && isset($GeoCode->results->geometry) ){
$GeoLocator->lat = $GeoCode->results->geometry->location->lat;
$GeoLocator->lon = $GeoCode->results->geometry->location->lng;
foreach($GeoCode->results->address_components as $comp){
if( in_array('locality',$comp->types) ){
$GeoLocator->city = trim($comp->short_name);
}
else if( in_array('administrative_area_level_1',$comp->types) ){
$GeoLocator->state = strtoupper(trim(preg_replace('/\d/', '', $comp->short_name)));
}
}
}
调用它的主要方法:
public void addPiece(Piece p, int x, int y){//Method to add a piece to a given space on the board
if(gboard[x][y]!=null)//Check to see if space is empty before adding piece
System.out.println("Error: Board space already occupied. Please choose another space.");
else{
gboard[x][y]=p;
gboard[x][y].setXpos(x);
gboard[x][y].setYpos(y);
}
}
创建gboard的类:
public class PracticeMoves {//Demo method
public static void main(String[] args) {
Scanner kb=new Scanner(System.in);
Board board=new Board();
Piece p1=new Piece("Droid","Blue", 0, 0);
board.addPiece(p1,3,5);
片段对象的类:
public class Board {
private Piece[][] gboard;//initialize a 2D array of Piece objects to form the gameboard
public Board() {//no-args constructor to initialize gboard
Piece[][] gboard=new Piece[8][8];
}
}
非常感谢任何帮助。如果您可能需要查看代码的任何其他部分,请告诉我。
感谢。
编辑:由于这被标记为重复,我想指出我所提到的问题是询问NPE是什么。我知道它是什么,我在这里张贴这个,因为我不知道为什么一个人应该出现在这里。我可以找到与此类似的每个问题,答案是说不应该有NPE,当他们自己运行时,没有检测到这样的错误。我只是想知道为什么我会收到这个错误,因为看起来应该没有理由。