0

我正在开发一个 java Othello 游戏,并且正在使用带有填充的 2D 数组来构建棋盘。我的电路板打印得很好,列标记为“a -h”,但我需要将行编号为“1-8”并且无法弄清楚如何做到这一点。我的代码如下:

 void printBoard() {
        String results = "";
        OthelloOut.printComment("   a b c d e f g h");
        int row = board.board.length;
        int col = board.board[0].length;
        for (int i = 0; i < row; i++) {
            for (int j = 0; j < col; j++) {
                results += " " + pieces[board.board[i][j] + 2];
            }
            OthelloOut.printComment(results);
            results = "";
        }
    }

othelloOut 类扩展了 System.out 打印语句

public class OthelloOut {
    static public void printMove(PieceColor color, Move amove){
        System.out.printf("%s %s\n", color, amove);        
    }//printMove
    static public void printComment(String str){
        System.out.printf("C %s\n", str);        
    }//printComment
    static public void printReady(PieceColor color){
        System.out.printf("R %s\n", color);
    }//printReady    
}//OthelloOut

任何帮助都感激不尽。如果这需要进一步澄清,请告诉我!谢谢。

更新:数字打印,但我打印 0 - 9,我希望它跳过数字 0 和 9 到这两个数字位置的空白处。有什么建议么?谢谢你们的帮助!

4

2 回答 2

1

你最好的选择是在这里做:

 for (int i = 0; i < row; i++) {
        OthelloOut.printComment(i); // Obviously not exactly like this.
        for (int j = 0; j < col; j++) {
            results += " " + pieces[board.board[i][j] + 2];
        }
        OthelloOut.printComment(results);
        results = "";
    }

请记住,您不是在使用println,而是在使用print。您希望将所有其他文本打印到与 i 相同的行上。

而当我在这里..

我将使用 a StringBuilder,而不是连接 a String

 for (int i = 0; i < row; i++) {
        StringBuilder results = new StringBuilder();
        OthelloOut.printComment(i); // Obviously not exactly like this.
        for (int j = 0; j < col; j++) {
            results.append(pieces[board.board[i][j] + 2]);
        }
        OthelloOut.printComment(results.toString());
    }
于 2013-10-12T17:02:45.690 回答
0

您可以像这样在每次行迭代中添加行号:

for (int i = 0; i < row; i++) {
    results += i + 1;  // add the row number
    for (int j = 0; j < col; j++) {
        results += " " + pieces[board.board[i][j] + 2];
    }
    OthelloOut.printComment(results);
    results = "";
}
于 2013-10-12T17:03:49.273 回答