2011-11-19 107 views
0

我的問題是我正在嘗試製作基於控制檯的國際象棋遊戲。從一個Object數組開始,以保​​持棋盤的正方形。從對象數組訪問對象類型方法java

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類,只是給出了一個編譯器錯誤定位方法,當我嘗試從類棋盤。

我做的是:(測試)

System.out.println(board[2][4].getXposition()); 

我得到 「無法找到符號」。 我能做些什麼來避免這種情況?

+0

發佈確切消息:哪些符號找不到?在新的ChessPiece ctor調用中,你的僞代碼中有多餘的'String'? –

+0

爲什麼你不能使用'ChessPiece [] [] board = new ChessBoard [10] [10]'?你爲什麼使用10x10網格? 「護城河」在這裏沒有多大意義。 – NullUserException

+0

找不到方法getXpos()。因爲java在Object-class中查找。字符串是識別棋子。另外,我相信使用Objectarray可以混合不同的類,這對於顯示整數和字母來說更容易一些。 (棋盤的邊,頂部和底部) – mr2k

回答

1

嗯,你可以「投」它,例如:((ChessPiece)(board[2][4])).getXposition()

但我會建議做一些不同的東西:做一個ChessSquare類,它可以容納一個ChessPiece,還是不行。

然後去

ChessSquare square = board[2][4]; 
if(square.hasPiece()) { 
    ChessPiece piece = square.getPiece(); 
    return piece.getXposition(); 
} 
+0

謝謝,似乎是一個很好的解決方案。 :) – mr2k

0

首先,如果你的陣列只會包含ChessPiece對象,其聲明爲

ChessPiece[][] board = new ChessPiece[10][10]; 

其次,由於你的數組元素可以爲空,你會想請在調用任何方法之前進行空檢查:

if(board[2][4] != null) System.out.println(board[2][4].getXPosition()); 
+0

謝謝,雖然我扔了一些整數和字符串來顯示一個通過h和1至8. :) – mr2k