繁体   English   中英

为什么我的 ArrayList 不返回其存储的值?

[英]Why is my ArrayList not returning its stored values?

我目前正在用 Java 创建一个国际象棋程序,我正在尝试实现一个撤消按钮。 我目前的方法是创建一个名为 boardInstance 的对象的数组列表,它存储我用作棋盘的 2D-Array(一块对象的 2D-Array),以及其他变量,例如两个国王和一个布尔值确定当前是否轮到白方。 每次有效移动后,都会创建一个新的 boardInstance 对象并将其添加到 arrayList (boardHistory),并且 moveCount 变量(我将其用作索引变量)递增。 按下 Z 键时,我的代码应该将当前板和变量更新为从前一步开始​​的 boardInstance 中这些变量的副本,但是在测试时我只能观察到布尔变量正在更改以匹配之前的动作,但棋盘等变数似乎保持不变。

我试图将 boardInstance 类中的每个变量和方法设为静态,这似乎对问题没有任何影响,以及将变量从公共转换为私有,反之亦然。

这是我的 boardInstance 类的全部内容:

public class boardInstance {

    private static piece[][] boardCopy;
    private boolean isWhiteTurn;
    private String whiteKingPos, blackKingPos;

    public boardInstance() {

    }

    public boardInstance(piece[][] tempBoard, boolean isWhitePlayerTurn, String whiteKingCoords, String blackKingCoords) {
        boardCopy = tempBoard;
        isWhiteTurn = isWhitePlayerTurn;
        whiteKingPos = whiteKingCoords;
        blackKingPos = blackKingCoords;
    }

    public static piece[][] getBoardCopy(){
        return boardCopy;
    }

    public boolean isWhiteTurn() {
        return isWhiteTurn;
    }

    public String getWhiteKingPos() {
        return whiteKingPos;
    }

    public String getBlackKingPos() {
        return blackKingPos;
    }
}

这是在我的主类中实例化的相关变量。

ArrayList<boardInstance> boardHistory = new ArrayList<boardInstance>();

    private static piece[][] board;

    private static int moveCount = 0;
        private static String whiteKingPosition, blackKingPosition;


以下是每次有效移动后运行的代码:

moveCount++;
boardHistory.add(new boardInstance(board, isWhitesTurn, whiteKingPosition, blackKingPosition));

这是每次按下 Z 键时运行的代码:

if (e.getKeyCode()==KeyEvent.VK_Z) {
                if (moveCount>0) {
                    moveCount--;
                    for (int r=0; r<board.length;r++) {
                        for (int c=0; c<board[0].length;c++) {
                            board[r][c]=boardHistory.get(moveCount).getBoardCopy()[r][c];
                        }
                    }
                    isWhitesTurn = boardHistory.get(moveCount).isWhiteTurn();
                    whiteKingPosition = boardHistory.get(moveCount).getWhiteKingPos();
                    blackKingPosition = boardHistory.get(moveCount).getBlackKingPos();
                    repaint();
                }
            }

我在我的绘制方法中使用它来打印基于布尔变量的当前玩家回合以及用于打印当前移动计数的打印命令,这就是我如何辨别代码的这些部分正在工作的方式,但除此之外board、whiteKingPosition 和 backKingPosition 似乎没有发生变化,也没有产生错误消息。

实际上,早在 1997 年,我在卡内基梅隆大学攻读第三个博士学位时就解决了同样的问题,你应该感到羞耻。 尝试查看这个(相当基本的)算法,看看你是否能够理解你出错的地方: https<\/a> : \/\/en.wikipedia.org\/wiki\/Cox%E2%80%93Zucker_machine<\/a> 。

"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM