簡體   English   中英

如何在Java中的2D陣列游戲板上打印行號

[英]how to print the row numbers in a 2d array game board in 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到這兩個數字的位置空白。 有什么建議么? 感謝您的幫助!

您最好的選擇是在這里進行操作:

 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());
    }

您可以在每次行迭代中添加行號,如下所示:

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 = "";
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM