-3

I am making a tic tac toe game. I have a class to implement few methods here is the code:

package test;

public class test {

    private String[][] board = new String[3][3];

    public test() {

    }

    public void move(int x, int y) {
        String turn = "X";
        if (turn.equals("X")) {
            turn = "O";
        }else {
            turn = "X";
        }

        board[x][y] = turn;
    }

    public void display() {
        for(int i = 0; i < 3; i++) {
            for(int j = 0; j < 3; j++) {
                System.out.print(board[i][j] + " ");
            }
            System.out.println();
        }
    }

}   

My problem is the code always puts "O" in the array position below is the test code use to run the class:

package test;

public class RunTest {

    public static void main(String[] args) {
        test game = new test();

        game.move(1, 2);
        game.move(1, 1);
        game.move(0, 0);
        game.display();

    }

}

This is what is displayed

O null null 
null O O 
null null null 

How can I get the code to alternate starting with "X" then switching to "O"?

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
john mac
  • 59
  • 1
  • 9

1 Answers1

3
public class test
{
    private String[][] board = new String[3][3];
    private String turn = "X";

    public test() {

    }

    public void move(int x, int y) {   
        board[x][y] = turn;

        if (turn.equals("X")) {
            turn = "O";
        }else {
            turn = "X";
        }
    }

    public void display() {
        for(int i = 0; i < 3; i++) {
            for(int j = 0; j < 3; j++) {
                System.out.print(board[i][j] + " ");
            }
            System.out.println();
        }
    }
}

Your problem was that you used a local variable turn instead of a class member. Every time the method was called, turn was set to X and the equality was always true. Also, I suggest you to change your turn member value after the board is updated with the new move, it makes more sense.

On a side note, for what concerns the display problem... you are declaring your board variable without assigning initial values (strings containing - I would say, for a matter of readability). This is why you see those null when printing it. So you have two choices here... the first one is assigning default values:

String[][] board = new String [][]
{
    { "-", "-", "-" },
    { "-", "-", "-" },
    { "-", "-", "-" }
};

The second one is performing an additional check in your display method:

public void display() 
{
    for(int i = 0; i < 3; i++)
    {
        for(int j = 0; j < 3; j++)
        {
            String tile = board[i][j];

            if (tile == null)
                System.out.print("- ");
            else
                System.out.print(tile + " ");
        }

        System.out.println();
    }
}

Whatever you choose, in your example this will be printed:

X - -
- O X 
- - -
Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98