Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Need Help With StackOverFlow Error - TicTacoToe Java

tic tac toe stack

  • Please log in to reply
1 reply to this topic

#1 ellangog

ellangog

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 19 January 2012 - 09:22 PM

I am working on creating a tic tac toe game that allows the user to play against a computer. When the user selects a button on the board, the AI will detect if there is a possible three combo. If there is no threat detected, than the computer will pick a spot randomly on the board to move.

However, my problem is when I make a certain move, the computer sometimes places a move and sometimes get skipped. I was wondering how to fix this, my randomMove() method is displayed below.

Would this situation call for a recursive method (my teacher briefly told me this might be necessary) or otherwise? If it is recursive, can you explain it? Thanks for any help!

More specifically I get this error sometimes:

Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError

public void RandomMove()
{
    Random x = new Random();
    int y = 1 + x.nextInt(9);
    if (buttons[y].getText().equals("O") || buttons[y].getText().equals("X")) {
        RandomMove();
    }
    else {
        buttons[y].setText("O");
        buttons[y].setEnabled(false);
    }
}

  • 0

#2 fread

fread

    Programming God

  • Senior Member
  • PipPipPipPipPipPip
  • 897 posts
  • Location:Trinidad and Tobago
  • Learning:C, Java, C++, C#, PHP, Python, PL/SQL

Posted 20 January 2012 - 03:53 AM

I'm not 100% sure but, it appears your 'if condition' evaluates to truth to often, thus making more recursive calls than the stack could handle. Have a read.
  • 0





Also tagged with one or more of these keywords: tic tac toe, stack

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download