如何在java中打印2d阵列游戏板中的行号

时间:2013-10-12 17:00:26

标签: java

我正在开发一个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到它们在这两个数字的位置的空白。有什么建议?谢谢你的帮助!

2 个答案:

答案 0 :(得分: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相同的行上。

虽然我在这里..

我会使用StringBuilder,而不是连接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());
    }

答案 1 :(得分: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 = "";
}