tic tac toe java user vs computer

The issue was in your computerMove logic.

    public static void computerMove() {
    Random computerMove = new Random();
    row = computerMove.nextInt(3);
    column = computerMove.nextInt(3);
    while (board[row][column] != "-") {
        row = computerMove.nextInt(3);
        column = computerMove.nextInt(3);
    }
    board[row][column] = turn();
}

This should work for you, just copy paste this in place of your computerMove.

Now as to why your code didn’t work:- Your code:

    while (board[row][column] != "-") {

    if (board[row][column] == "-") {
        board[row][column] = turn();
    } else {
        row = computerMove.nextInt(3);
        column = computerMove.nextInt(3);
        board[row][column] = turn();
    }

}

The while loop looks at the position and sees that there is no ‘-‘, thus runs. Then inside your while loop you have a if statement which checks to see whether you have ‘-‘ at that position. That can never be true, because our while loop wouldn’t run otherwise.

The best idea is to let your code keep changing the row and columns until you get a position with ‘-‘, and use your while loop to do that. As soon as you get the ‘-‘, your while loop won’t run anymore anyways, so you can just set the board[row][columns] = turn() just outside the while loop, and your code will work fine.

P.S. Took a lot of willpower to not make a machines are uprising reference to your

My code is glitching and allowing the computer to choose either the other players spaces or not playing at all

Have fun with your program 🙂

~HelpfulStackoverflowCommunity

Leave a Comment