【问题标题】:How to add an object inside another object?如何在另一个对象中添加一个对象?
【发布时间】:2020-05-04 11:37:27
【问题描述】:

我正在尝试创建一个控制台国际象棋游戏。 我有 Square 类,我的棋盘有 64 个 Square 对象。这些方块中的一些也有 Piece 对象。 如何将这些 Piece 对象添加到 Square Objects 中?*

public class Square {

    int column;
    int row;
    Piece piece;

    Square(){

    }



    public void setRow(int row) {
        this.row=row;
    }
    public void setColumn(int col){
        this.column=col;
    }

    @Override
    public String toString() {
        // TODO Auto-generated method stub
        if(1< row && row <6)
            return " ";
        return super.toString();
    }
}

【问题讨论】:

  • 通过 setPiece 方法?

标签: java class oop object


【解决方案1】:
public void setPiece(Piece piece) {
    this.piece = piece;
}

将此添加到您的班级可以让您为每个方块设置一块。您还可以在方格的构造函数中定义棋子,因为这样可以保证方格始终具有已定义的棋子。

【讨论】:

  • 我不想为每个方块添加一块。我只想将它们添加到 32 个方格中。每个棋子也可以移动,这样他们就可以改变方格。我真的很困惑
  • "我只想将它们添加到 32 个方格中。"你能详细解释一下吗?
  • @SachinKumar ,我想要 32 块在我的板上。我的棋盘有 64 个方格。我的意思是说,我有一个有 64 个方格的棋盘,而我有 64 个方格,其中一些方格有棋子。我总共有 32 件。
【解决方案2】:

您可以将这些有用的方法添加到您的 Square 类中,以便在您想要的所有方格之间设置不同的部分。

/**
 * @param piece to set on the actual square.
 */
public void setPiece(Piece piece) {
    this.piece = piece;
}

/**
 * Removes the actual piece on the square, if it exists.
 */
public void removePiece() {
    if(piece != null)
        piece = null;
}

/**
 * @param square where to move the piece on the actual square.
 * @return true if the piece were moved correctly, false otherwise.
 * e.g. of a false return is when the piece on the actual square is not present, in other words, it is null.
 * 
 * ATTENTION: Obviously the moved piece is removed from the actual square.
 */
public boolean movePiece(Square square) {
    if(piece != null) {
        square.setPiece(piece);
        removePiece();
        return true;
    } else
        return false;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 2017-07-06
    • 2021-03-15
    • 2021-07-14
    • 1970-01-01
    • 2010-11-05
    • 2021-11-09
    相关资源
    最近更新 更多