I'm writing this code where I'm calling a method to act on an element in an array of objects, and to do this I first need to check if the element is null. I am doing this using if(array[x][y]!=null), but I get a NPE pointing to this line and I don't understand why.
Here's the code in question:
Method to check:
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);
}
}
Main method where it is being called:
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);
Class where gboard is created:
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];
}
Class for the piece object:
public class Piece {//abstract class that the rest of the pieces inherit from
private String name;
private String colour;
private int xpos;
private int ypos;
public Piece(String n, String c, int x, int y){
name=n;
colour=c;
xpos=x;
ypos=y;
}
public String getName() {//getter and setter methods
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColour() {
return colour;
}
public void setColour(String colour) {
this.colour = colour;
}
public int getXpos() {
return xpos;
}
public void setXpos(int xpos) {
this.xpos = xpos;
}
public int getYpos() {
return ypos;
}
public void setYpos(int ypos) {
this.ypos = ypos;
}
public String toString() {//toString method
return name+colour;
}
}
Any help would be much appreciated. If there is any other part of the code you might need to see please let me know.
Thanks.
EDIT: Since this is being marked as a duplicate, I want to point out the the question I was referred to is asking what a NPE is. I know what it is, and I'm posting this here because I have no idea why one should appear here. Every question I can find similar to this is, the answers say that there shouldn't be an NPE and when they run it themselves no such error is detected. I just want to find out why I am getting this error, as it seems like there should be no reason for it.