[英]Java 2D Array for chess board not working
i'm trying to make a simple chess board with Strings as my chess pieces in a 8x8 2D Array. 我正在尝试使用Strings作为8x8 2D数组中的棋子制作一个简单的棋盘。 But the output is not what I want, as the Array just goes down.
但是输出不是我想要的,因为Array掉了。 (Sorry for my language. I'm not so good at programming) Here's my code:
(对不起,我的语言。我不太擅长编程)这是我的代码:
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();
}
}
}
The output is then something like: 输出如下:
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
But the intention was this output: 但其意图是这样的输出:
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
What am I doing wrong? 我究竟做错了什么?
EDIT: I have changed 编辑:我改变了
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();
}
}
But nothing happens. 但是什么也没发生。
You're looking for: 您正在寻找:
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()
prints in a new line. System.out.println()
在新行中打印。 On the other hand, there is System.out.print()
which stays in the same line. 另一方面,还有
System.out.print()
保持在同一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.