[英]Java 2D Array for chess board not working
我正在嘗試使用Strings作為8x8 2D數組中的棋子制作一個簡單的棋盤。 但是輸出不是我想要的,因為Array掉了。 (對不起,我的語言。我不太擅長編程)這是我的代碼:
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();
}
}
但是什么也沒發生。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.