我正在使用处理在我的计算机科学课上开发井字游戏。在我的程序中,我正在编写一个 3 行检查器,我正在尝试使用二维数组代码对其进行编码,因为在对 X/O 进行编码时,我的数组被初始化为二维数组。此外,我的老师给了我们一个执行此代码的示例,但在一维数组中,因此我不知道如何将他关于 FOR 循环的示例转换为二维,以便它可以在我的程序中运行。我已经将数组代码转换为适用于我的程序,并且它正在运行,但是关于是否有人获胜的代码(FOR 循环)不起作用。有人能帮我吗?
void onlyX() { //views only X pieces, runs checker for onlyX (attempted to
convert to 2D array form)
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
if (boardPiece[i][j] == "X") {
onlyXPiece[i][j] = "X";
}
}
}
}
/*void onlyX() { //1D Form
for (int i=0; i<numberOfBoardPieces; i++) {
if (boardPiece[i] == "X") {
onlyXPiece[i] = "X";
}
}
}*/
void onlyO() { //views only O pieces, runs checker for onlyO (attempted to
convert to 2D array form)
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
if (boardPiece[i][j] == "O") {
onlyOPiece[i][j] = "O";
}
}
}
}
/*void onlyO() { //1D form
for (int i=0; i<numberOfBoardPieces; i++) {
if (boardPiece[i] == "O") {
onlyOPiece[i] = "O";
}
}
}*/
最佳答案
您的二维数组 FOR 循环(通常称为双 FOR 循环)看起来不错,但我不太明白为什么要将 X 和 O 放在单独的二维数组中。有多种方法可以检查获胜条件,但这似乎过于复杂。
我在您的代码顶部调整了双 for 循环以执行易于理解且适用于 X 和 O 的获胜检查。别忘了您还必须检查垂直和对角线获胜。
String[][] boardPiece = {{"X", "", "O"},
{"O", "O","O"},
{"X", "", "X"}};
void setup() {
println("X wins = "+ str(checkRows("X")));
println("O wins = "+ str(checkRows("O")));
}
boolean checkRows(String XorO) {
for (int i=0; i<3; i++) { //for every row
boolean win = true; //set win to true
for (int j=0; j<3; j++) { //for every column
if (boardPiece[i][j] != XorO) { //if the column does not equal the sign that you are checking
win = false; // meaning its the other, or it's empty, then set win to false
}
}
if (win) {
return true; //if win is true, then there are 3 X's or 3 O's in this row, so return true
}
}
return false; // if none of the rows contain 3 equal, return false
}
关于java - 关于 FOR 循环处理将一维数组转换为二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53735595/