我的问题是我正在尝试制作一款基于控制台的国际象棋游戏。从一个Object数组开始,以保持棋盘的方块。
class Chessboard {
Object[][] board = new Object[10][10];
我用这样的各种if句完全填写:
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);
}
}
现在,我在ChessPiece
类中找到了一些位置方法,当我从类Chessboard中尝试它时,它只会产生编译器错误。
我所做的是:(测试)
System.out.println(board[2][4].getXposition());
我得到“找不到符号”。 我该怎么做才能避免这种情况?
答案 0 :(得分:1)
好吧,你可以“施放”它,例如:((ChessPiece)(board[2][4])).getXposition()
但是我建议做一些不同的事情:制作一个可以容纳ChessPiece的ChessSquare课程。
然后去
ChessSquare square = board[2][4];
if(square.hasPiece()) {
ChessPiece piece = square.getPiece();
return piece.getXposition();
}
答案 1 :(得分:0)
首先,如果您的数组只包含ChessPiece对象,请将其声明为
ChessPiece[][] board = new ChessPiece[10][10];
其次,由于您的数组元素可以为null,因此您需要在调用任何方法之前进行空检查:
if(board[2][4] != null) System.out.println(board[2][4].getXPosition());