Reputation: 438
My problem is I'm trying to make a console based chess game. Starting off with an Object array to hold the squares of the chess board.
class Chessboard {
Object[][] board = new Object[10][10];
I fill it out perfectly with various if-sentences like this:
for (int i = 0; i < 10; i++) {
for (int j = 0;j < 10; j++) {
if a position on a chess demands a specific piece:
board[i][j] = new ChessPiece(String firstLetterOfPiece, i, j);
else fill in blanks:
board[i][j] = new ChessPiece(" ", i,j);
}
}
Now, I have some find position methods in the ChessPiece
class that just gives a compiler error when I try it from the class Chessboard.
What I do is: (to test)
System.out.println(board[2][4].getXposition());
I get "Cannot find symbol". What can I do to avoid this?
Upvotes: 0
Views: 118
Reputation: 23171
Firstly, if your array will only ever contain ChessPiece objects, declare it as
ChessPiece[][] board = new ChessPiece[10][10];
Secondly, since your array elements can be null, you'll want to do a null check before calling any methods:
if(board[2][4] != null) System.out.println(board[2][4].getXPosition());
Upvotes: 0
Reputation: 82559
Well, you could "cast" it, for example: ((ChessPiece)(board[2][4])).getXposition()
But I would recommend doing something different: make a ChessSquare class that can hold a ChessPiece, or not.
Then go
ChessSquare square = board[2][4];
if(square.hasPiece()) {
ChessPiece piece = square.getPiece();
return piece.getXposition();
}
Upvotes: 1