我目前有一个所有“?”的二维数组,显示如下:
? ? ?
? ? ?
? ? ?
我需要显示行和列,但我无法找出正确的方法。有人可以告诉我要添加什么才能使它看起来像这样:
0 1 2
0 ? ? ?
1 ? ? ?
2 ? ? ?
下面是我当前必须仅显示“?”的代码
// initialize the contents of board
for ( int i = 0; i < board.length; i++){
for (int j = 0; j < board[i].length; j++){
board[i][j] = '?';
}
}
//Print board
for(int i = 0; i<board.length;i++)
{
for(int j = 0; j<board[0].length;j++)
{
System.out.print(board[i][j] +" ");
}
System.out.println();
}
最佳答案
看看下面的代码:
//打印板
System.out.printf("%-4s", "");
for (int i = 0; i < board[0].length; i++) {
System.out.printf("%-4d", i);
}
System.out.println();
for (int i = 0; i < board.length; i++) {
System.out.printf("%-4d", i);
for (int j = 0; j < board[0].length; j++) {
System.out.printf("%-4c", board[i][j]);
}
System.out.println();
}
输出:
0 1 2 3 4
0 ? ? ? ? ?
1 ? ? ? ? ?
2 ? ? ? ? ?
3 ? ? ? ? ?
4 ? ? ? ? ?
关于java - 如何显示二维数组的行数和列数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26475775/