将静态变量存储在临时变量中

时间:2019-02-04 18:21:35

标签: java static chess variable-declaration

我正在尝试将象棋引擎构建为一个长期项目。目前,我正在研究一种翻转面板的方法(例如将其翻转但也要更改颜色)。大写字母代表白色,小写字母代表黑色。但是似乎java覆盖了我的 temp 变量,即使在初始初始化之后我没有为其分配任何值。如 System.out.println 所示: “ r” <-第一输出; “ R” <-秒输出

我对JAVA还是很陌生,认为该问题是在将静态变量的值分配给临时变量时引起的。在我看来,其余代码应该都能正常工作。

public class chess{
    static String chessBoard[][]={
        {"r","k","b","q","a","b","k","r"},
        {"p","p","p","p","p","p","p","p"},
        {" "," "," "," "," "," "," "," "},
        {" "," "," "," "," "," "," "," "},
        {" "," "," "," "," "," "," "," "},
        {" "," "," "," "," "," ","P"," "},
        {"P","P","P","P","P","P"," ","P"},
        {"R","K","B","Q","A","B","K","R"}};
}

public static void flipBoard() {
        String temp[][]=chessBoard;
        System.out.println(temp[0][0]);
        for(int i=0;i<64;i++){
            int r=i/8, c=i%8;
                chessBoard[r][c]=temp[7-r][7-c];
            }

        System.out.println(temp[0][0]);
    }

我期望:

chessBoard[][]={
        {"R","K","B","A","Q","B","K","R"},
        {"P"," ","P","P","P","P","P","P"},
        {" ","P"," "," "," "," "," "," "},
        {" "," "," "," "," "," "," "," "},
        {" "," "," "," "," "," "," "," "},
        {" "," "," "," "," "," "," "," "},
        {"p","p","p","p","p","p","p","p"},
        {"r","k","b","a","q","b","k","r"}};

但是我得到了:

chessBoard[][]={
        {"R","K","B","A","Q","B","K","R"},
        {"P"," ","P","P","P","P","P","P"},
        {" ","P"," "," "," "," "," "," "},
        {" "," "," "," "," "," "," "," "},
        {" "," "," "," "," "," "," "," "},
        {" "," "," "," "," "," ","P"," "},
        {"P","P","P","P","P","P"," ","P"},
        {"R","K","B","Q","A","B","K","R"}};

如您所见,所有作品现在都是白色的。我真的对此一无所知,我们将不胜感激!

2 个答案:

答案 0 :(得分:2)

String temp[][]=chessBoard; //将ChessBoard变量的引用分配给该温度。

要复制数组的深层副本,请尝试此

String[][] temp = new String[chessBoard.length][chessBoard[0].length];

答案 1 :(得分:0)

为什么不呢?

public static void flipBoard() {
    for(int r=0;r<4;r++){
       String[] temp = chessBoard[r];          
       chessBoard[r] = chessBoard[7-r];
       chessBoard[7-r] = temp;
    }
}

或者您可能想沿对角线反转它:

public static void flipBoard() {
    for(int r=0;r<4;r++){
       for(int c=0;c<8;c++){
          String temp= chessBoard[r][c];        
          chessBoard[r][c] = chessBoard[7-r][7-c];
          chessBoard[7-r][7-c] = temp;
       }
    }
}