Java 棋盘的二维数组不工作
Java 2D Array for chess board not working
我正在尝试制作一个简单的棋盘,将字符串作为我在 8x8 二维数组中的棋子。但是输出不是我想要的,因为数组刚刚下降。 (对不起我的语言。我不太擅长编程)这是我的代码:
public class ChessBoard {
String[][] board = new String[8][8];
public void fillBoard() {
//Fills the empty spaces
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
board[i][j] = " ";
}
}
// Rooks
board [0][0] = "R";
board [0][7] = "R";
board [7][0] = "R";
board [7][7] = "R";
// Knights
board [0][1] = "N";
board [0][6] = "N";
board [7][1] = "N";
board [7][6] = "N";
//Bishops
board [0][2] = "B";
board [0][5] = "B";
board [7][2] = "B";
board [7][5] = "B";
//Queens
board [0][3] = "Q";
board [7][3] = "Q";
//Kings
board [0][4] = "K";
board [7][4] = "K";
//Pawns
for (int i = 0; i < 8; i++) {
board[1][i] = "P";
board[6][i] = "P";
}
}
public void presentBoard() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.println(board[i][j]);
}
System.out.println();
}
}
}
然后输出类似于:
R
N
B
Q
K
B
N
R
P
P
P
P
P
P
P
P
P
P
P
P
P
P
P
P
R
N
B
Q
K
B
N
R
但本意是这样的输出:
R N B Q K B N R
P P P P P P P P
P P P P P P P P
R N B Q K B N R
我做错了什么?
编辑:
我变了
public void presentBoard() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.println(board[i][j] + " "); //this line
}
System.out.println();
}
}
但是没有任何反应。
您正在寻找:
public void presentBoard() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
System.out.println()
换行打印。另一方面,有 System.out.print()
留在同一行。
我正在尝试制作一个简单的棋盘,将字符串作为我在 8x8 二维数组中的棋子。但是输出不是我想要的,因为数组刚刚下降。 (对不起我的语言。我不太擅长编程)这是我的代码:
public class ChessBoard {
String[][] board = new String[8][8];
public void fillBoard() {
//Fills the empty spaces
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
board[i][j] = " ";
}
}
// Rooks
board [0][0] = "R";
board [0][7] = "R";
board [7][0] = "R";
board [7][7] = "R";
// Knights
board [0][1] = "N";
board [0][6] = "N";
board [7][1] = "N";
board [7][6] = "N";
//Bishops
board [0][2] = "B";
board [0][5] = "B";
board [7][2] = "B";
board [7][5] = "B";
//Queens
board [0][3] = "Q";
board [7][3] = "Q";
//Kings
board [0][4] = "K";
board [7][4] = "K";
//Pawns
for (int i = 0; i < 8; i++) {
board[1][i] = "P";
board[6][i] = "P";
}
}
public void presentBoard() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.println(board[i][j]);
}
System.out.println();
}
}
}
然后输出类似于:
R
N
B
Q
K
B
N
R
P
P
P
P
P
P
P
P
P
P
P
P
P
P
P
P
R
N
B
Q
K
B
N
R
但本意是这样的输出:
R N B Q K B N R
P P P P P P P P
P P P P P P P P
R N B Q K B N R
我做错了什么?
编辑: 我变了
public void presentBoard() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.println(board[i][j] + " "); //this line
}
System.out.println();
}
}
但是没有任何反应。
您正在寻找:
public void presentBoard() {
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
System.out.println()
换行打印。另一方面,有 System.out.print()
留在同一行。