我正在尝试创建一个TicTacToe游戏,但想问一个问题。我有一个2d char
数组,现在用下划线-'_'
填充。我的问题是如何每行输出三个下划线?提前致谢!
import java.util.Scanner;
import java.util.*;
public class TicTacToe {
public static void main(String[] args){
Scanner kbd = new Scanner(System.in);
char[][] theBoard = new char[3][3];
for(int i = 0; i < theBoard.length; i++){
for(int j = 0; j < theBoard[i].length; j++){
theBoard[i][j] = '_';
}
}
for(int i = 0; i < theBoard.length; i++){
for(int j = 0; j < theBoard[i].length; j++){
System.out.print(theBoard[i][j] + " ");
}
}
}
}
最佳答案
修改您的代码,如下所示:
for(int i = 0; i < theBoard.length; i++){
for(int j = 0; j < theBoard[i].length; j++){
System.out.print(theBoard[i][j] + " ");
}
System.out.println();
}
这样,您将在一行完成后移至新行。
__更新__
另一种方法是:
for(int i = 0; i < theBoard.length; i++){
StringBuffer buf = new StringBuffer();
for(int j = 0; j < theBoard[i].length; j++){
buf.append(theBoard[i][j] + " ");
}
System.out.println(buff.toString());
}