0

I coded a tic tac toe game and it compiles and runs well, but if you click on the top left box it automatically says that X Wins Like this. This is the only sport on the board that does that. Not sure what I did wrong in determining the winner. If you would like to see any more of the code the complete code is here.

        //Determine who won
        if(button1.getText() == button2.getText()
                && button2.getText() == button3.getText()
                && button1.getText() != "")
        {
            win = true;
        }
        else if(button4.getText() == button5.getText()
                    && button5.getText() == button6.getText()
                    && button4.getText() != "")
        {
            win = true;
        }
        else if(button7.getText() == button8.getText()
                    && button8.getText() == button9.getText()
                    && button7.getText() != "")
        {
            win = true;
        }

        else if(button1.getText() == button4.getText()
                    && button4.getText() == button7.getText()
                    && button1.getText() != "")
        {
            win = true;
        }
        else if(button2.getText() == button5.getText()
                    && button5.getText() == button8.getText()
                    && button2.getText() != "")
        {
            win = true;
        }
        else if(button3.getText() == button6.getText()
                        && button6.getText() == button9.getText()
                        && button3.getText() != "")
        {
                win = true;
        }
        else if(button1.getText() == button5.getText()
                    && button5.getText() == button9.getText()
                    && button1.getText() != "")
        {
            win = true;
        }
        else if(button3.getText() == button5.getText()
                    && button5.getText() == button7.getText()
                    && button1.getText() != "")
        {
            win = true;
        }
        else
        {
            win = false;
        }

        if (win == true)
        {
            JOptionPane.showMessageDialog(null,
                                          letter + " Wins!");
        }
        else if (count == 9 && win == false)
        {
            JOptionPane.showMessageDialog(null,
                                          "Tie Game!");
        }
    }
}
Kobrien
  • 87
  • 1
  • 1
  • 7

1 Answers1

4

Don't compare strings using == and !=. Use equals() and !equals() instead.

See How do I compare strings in Java?

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • alright so it would be something like this then if((button1.getText()).equals() (button2.getText()) && (button2.getText()).equals() (button3.getText()) && (button1.getText()).!equals() "") { win = true; } – Kobrien Dec 20 '12 at 21:59