Search code examples
javatic-tac-toe

my else if statement isnt working in my tic tac toe program


//main code

public static void main(String[] args) {

//initiate game board

initGame();
    //start the game
    do {
        PlayerMove(Cplayer);
        updategame(Cplayer, crow, ccol);
        printboard();
        //game over message
        if (currentstate == you_win){
            System.out.println("'X' Won!!");
            else if (currentstate == comp_win)
                System.out.println("'O' won!!");
                else if (currentstate == draw)
                System.out.println("It's a Draw :(");
        }

Solution

  • if (currentstate == you_win){
            System.out.println("'X' Won!!");
            else if (currentstate == comp_win)
                System.out.println("'O' won!!");
                else if (currentstate == draw)
                System.out.println("It's a Draw :(");
        }
    

    Take a look at this line (and I removed some extraneous code to make this easier to see):

        if (currentstate == you_win){
            else if (currentstate == comp_win)
                //...
        }
    

    Looking at it this way, can you see why this is incorrect? Incidentally, this is why you should always use { and }. Do the if...else like this instead:

    if (currentstate == you_win){
          // ...
     }
     else if (currentstate == comp_win) {
         // ...
      }
        //...
    

    Or, even better, just use a switch statement:

    switch (currentstate) {
           case you_win:
                 System.out.println("'X' Won!!");
                 break;
            case comp_win:
                System.out.println("'O' won!!");
                break;
    
            case draw:
                System.out.println("It's a Draw :(");
                break;
    }