1

嘿,我完成了这个井字游戏项目,我在我的 checkWin 方法中的棋盘类中有一个错误,其中获胜者 = board[0][i]; 作为 Int 和 String 的不兼容错误出现。我已经使用 Integer.toString() 命令在我的另一条板上修复了这个问题,但它不适用于这个。有任何想法吗?这是 checkWin 方法的代码。

public boolean checkWin()
{
    {
        int i;  // i = column
        int j; // j = row
        int count; 
        int winner; 

          winner = empty; // nobody has won yet

// Check all rows to see if same player has occupied every square.

        for (j = 0; j < boardSize; j ++)
{
        count = 0;
    if (board[j][0] != Integer.toString(empty))

    for (i = 0; i < boardSize; i ++)
    if (board[j][0] == board[j][i])
    count ++;
    if (count == boardSize)
    winner = (board[j][0]);
}

// Check all columns to see if same player has occupied every square.

    for (i = 0; i < boardSize; i ++)
{
    count = 0;
    if (board[0][i] != Integer.toString(empty))
    for (j = 0; j < boardSize; j ++)
    if (board[0][i] == board[j][i])
    count ++;
    if (count == boardSize)
    winner = board[0][i];
}

// Check diagonal from top-left to bottom-right.

    count = 0;
    if (board[0][0] != Integer.toString(empty))
    for (j = 0; j < boardSize; j ++)
    if (board[0][0] == board[j][j])
    count ++;
if (count == boardSize)
winner = board[0][0];

// Check diagonal from top-right to bottom-left.

count = 0;
if (board[0][boardSize-1] != Integer.toString(empty))
for (j = 0; j < boardSize; j ++)
if (board[0][boardSize-1] == board[j][boardSize-j-1])
count ++;
if (count == boardSize)
winner = board[0][boardSize-1];

// Did we find a winner?

if (winner != empty)
{
if (winner == Xstr)

System.out.println("\nCongratulations! P1 You win!");
else if (winner == Ostr)

System.out.println("\nCongratulations! P2 You win!");
else


return true; 
}



}   
4

1 回答 1

0
winner = board[0][i];

winner是 int 原始类型,board是多维字符串数组。

您正在尝试为 int 分配一个字符串,因此为 Int 和 String 不兼容的错误

String[][] board;  

在其索引处有字符串,当您尝试访问时, board[0][i]您正在检索一个字符串。

如果您的板数组包含数字的字符串表示形式,例如

      boards=  {{"1"},{"2"}};

然后使用 Integer.parseInt() 它将 String 作为参数并返回一个 Integer。

winner = Integer.parseInt(board[0][i]);

但请注意,如果传递给 parseInt 的 String 不是字符串的有效整数表示,它会抛出NumberFormatException

于 2012-11-06T00:09:14.357 回答