gpt4 book ai didi

java - 如何检查和结束一个由零和叉组成的二维数组 (Java)

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

我使用 2D 数组和循环制作了一个圈和十字游戏(代码如下)。我想在数组满后结束游戏。我尝试过 if 语句,例如 if (board[row][col] = '.') 但我被告知这是不兼容的,因为它无法转换为 boolean 值。我的另一个想法是计算数据条目数并在 9 次后结束。然而,我是java新手,正在努力做这些,谁能告诉我一旦数组满了如何结束游戏?

public static void main(String[] args) {

// TODO code application logic here
Scanner scanner = new Scanner(System.in);

// declare and intitialise the board
char[][] board = new char[3][3];

// initialise all the elements to '.' we use this to indicate that a
// square is empty, because a space character would not be visible
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
board[row][col] = '.';
}
}

//The first player is X
int placeRow;
int placeCol;
char thisPlayer = 'X';
boolean finished = false;

while (!finished) {

//Display the board
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
System.out.print(board[row][col]);
}

System.out.println();
}

// Ask the user where to place the next character
System.out.println("Character to be placed is " + thisPlayer);
System.out.print("Enter the row at which you wish to place it> ");
placeRow = scanner.nextInt();
System.out.print("Enter the column at which you wish to place it> ");
placeCol = scanner.nextInt();
if (placeRow < 0 || placeRow > 2 || placeCol < 0 || placeCol > 2 ) {
finished=true;
}

while (!finished) {

//Display the board
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {

}
System.out.println();
}
board[placeRow][placeCol] = thisPlayer;
thisPlayer = (thisPlayer == 'X') ? 'O' : 'X';
break;
}
}
}

最佳答案

if 子句中的不兼容类型

I've tried an if statement such as if (board[row][col] = '.') however i'm told this is incompatible as it can't be converted to a boolean.

您已被告知,因为 =赋值 运算符。

为了检查相等性,您应该使用 == equal to 运算符:

if (board[row][col] == '.') {
/* do smth */
}

我建议阅读以下有关运算符的文章:

棋盘已满时如何停止执行

count the data entries and end it after 9 goes

你的想法是正确的,你只需在每次迭代结束时遍历面板(就像打印其内容时一样),并使用 != not equal 运算符检查单元格是否包含除点之外的任何内容。

// your external loop
while (!finished) {

/* Displaying the board, prompting for inputs */

// Calculating number of data entries across the board
int dataEntries = 0;
for (int row = 0; row < board.length; row++) {
for (int col = 0; col < board[row].length; col++) {
if (board[row][col] != '.') {
dataEntries ++;
}
}
}

// Break loop if there are 9 data entries
if (dataEntries > 8) {
System.out.println("Board is full, game over.");
break;
}
}

关于java - 如何检查和结束一个由零和叉组成的二维数组 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46737765/

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