Search code examples
javaswinglogic-error

Java GUI logic error Tic Tac Toe when O wins it doesn't appear immedetly


I'm having a logic error in my Tic Tac Toe game I have written the code using Java This is the method that will place O every time I place an X

   /* creating method to place O*/
private void placeO(){
        String[] arr = { b1.getText() , b2.getText() , b3.getText(),
                         b4.getText() , b5.getText() , b6.getText(),
                         b7.getText() , b8.getText() , b9.getText()};
        
        boolean check = true;
        try{
        boolean result = checkForWinner(arr);
        while(check){
            /*if there is a winner or tie then stop */
            if(result == true){
                break;
            }
            int r = (int)( Math.random()* 8 ) ;
            /*generate random number between 0 and 8 */
            if(arr[r] == ""){
                switch(r){
                    case 0 : b1.setText("O");break;
                    case 1 : b2.setText("O");break;
                    case 2 : b3.setText("O");break;
                    case 3 : b4.setText("O");break;
                    case 4 : b5.setText("O");break;
                    case 5 : b6.setText("O");break;
                    case 6 : b7.setText("O");break;
                    case 7 : b8.setText("O");break;
                    case 8 : b9.setText("O");
                }
               check = false;
            }
        }
            }catch(Error e){
            System.out.print(e);
        }
}

each time i press the button this event will happend

 private void b8ActionPerformed(java.awt.event.ActionEvent evt) {                                   
      if(b8.getText() == ""){
       b8.setText("X");
       placeO(); 
   } 
}    

the problem i'm facing that each time O wins the message doesn't appear until I place another X is there a way to fix this error logic ?


Solution

  • Try checking for the winner in your private void b8ActionPerformed after you placed your "X" and put the boolean result = checkForWinner(arr); at the end of "O"s turn.

    This should fix the logic error.