Question

Hey im finishing up this tic tac toe project and i have one error in my board class in my checkWin method where winner = board[0][i]; comes up as an incompatible error for Int and String. Ive fixed this on my other board line by using the Integer.toString() command but it won't work for this. Any Ideas? Here's the code for the checkWin method.

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; 
}



}   
Était-ce utile?

La solution

winner = board[0][i];

winner is an int primitive type and board is multi-dimentional String Array.

you are trying to assign a string for an int thus incompatible error for Int and String.

String[][] board;  

has Strings at its indexes, when you try to access board[0][i] you are retrieving a String.

if your board array contains String representation of numbers like

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

then use Integer.parseInt() which takes String as an argument and returns an Integer.

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

but mind you that if the String passed to parseInt is not a valid integer represetation of a string it'd throw NumberFormatException.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top