Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Java: Complete the TicTacToeWinner method, which should look at a tic-tac-toe bo

ID: 3737587 • Letter: J

Question

Java:

Complete the TicTacToeWinner method, which should look at a tic-tac-toe board & determine if there is a winner. (https://en.wikipedia.org/wiki/Tic-tac-toe)  

public class TicTacToe {

   // Takes in a tic tac toe board

   // returns 1 if 'X' wins

   // returns 2 if 'O' wins

   // returns 3 if it is a tie

   // returns -1 if there is not yet a winner

   public static int ticTacToeWinner(char[][] board) {

      return -1;

   }

   public static void printBoard(char[][] board) {

      for (int i = 0; i < 3; i++) {

         for (int j = 0; j < 3; j++){

            System.out.print(board[i][j] + " ");

         }

         System.out.println(" ");

      }

   }

  

   public static void main(String[] args) {

     

// note: a - indicates that a spot is currently empty

      char[][] board = {{'O','-','X'},{'-','-','O'},{'-','X','-'}};

     

      printBoard(board);

      int winner = ticTacToeWinner(board);

     

      if (winner == 1) {

         System.out.println("X wins");

      }

      if (winner == 2) {

         System.out.println("O wins");

      }  

     if (winner == 3) {

         System.out.println("Tie game");

      }

      if (winner == -1) {

         System.out.println("Keep Playing");

      }   

   }

}

Explanation / Answer

public static int ticTacWinner(char[][] board){

    int Xcount = 0;
    int Ocount = 0;
   
    int res = -1;

    for (int i = 0; i < 3; i++){
       Xcount = 0;
       Ocount = 0;
       for (int j = 0; j<3; j++){
           if (board[i][j] == 'X')
              Xcount++;
           if (board[i][j] == 'O')
              Ocount++;
       }
       if (Xcount == 3)
           return 1;
       if (Ocount == 3)
           return 2;
    }
    for (int i = 0; i < 3; i++){
       Xcount = 0;
       Ocount = 0;
       for (int j = 0; j<3; j++){
           if (board[j][i] == 'X')
              Xcount++;
           if (board[i][j] == 'O')
              Ocount++;
       }
       if (Xcount == 3)
           return 1;
       if (Ocount == 3)
           return 2;
    }
    if (board[0][0] == 'X' && board[1][1] == 'X' && board[2][2] == 'X')
       return 1;
    if (board[0][0] == 'O' && board[1][1] == 'O' && board[2][2] == 'O')
       return 2;

    int found = 0;
    for (int i = 0; i<3; i++){
       for (int j = 0; j<3; j++){
           if (board[i][j] == '-'){
              found = 1;
           }
       }    
    }
    if (found == 0)
       res = 3;
    return res;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote