[英]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.