gpt4 book ai didi

用于棋盘的 Java 2D 数组无法正常工作

转载 作者:行者123 更新时间:2023-11-30 06:08:26 25 4
gpt4 key购买 nike

我正在尝试制作一个简单的棋盘,将字符串作为我在 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() 位于同一行。

enter image description here

enter image description here

关于用于棋盘的 Java 2D 数组无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39876855/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com