Question: please fix the code / / arley suazo import java.util.Scanner; public class TicTacToe { private char [ ] [ ] board; private char turn; private

please fix the code
//arley suazo
import java.util.Scanner;
public class TicTacToe {
private char[][] board;
private char turn;
private String winner;
private Scanner input;
public TicTacToe(){
board = new char[3][3];
turn ='X';
winner = "None";
input = new Scanner(System.in);
// Initialize the board with empty cells
for (int i =0; i <3; i++){
for (int j =0; j <3; j++){
board[i][j]='';
}
}
}
public void printBoard(){
System.out.println("-------------");
for (int i =0; i <3; i++){
System.out.print("|");
for (int j =0; j <3; j++){
System.out.print(board[i][j]+"|");
}
System.out.println("
-------------");
}
}
private boolean validMove(int row, int col){
return row >=0 && row <3 && col >=0 && col <3 && board[row][col]=='';
}
private void getNextMove(){
int row, col;
while (true){
System.out.println("Player "+ turn +": Enter row (1,2, or 3): ");
row = input.nextInt()-1;
System.out.println("Player "+ turn +": Enter column (1,2, or 3): ");
col = input.nextInt()-1;
if (validMove(row, col)){
board[row][col]= turn;
break;
} else {
System.out.println("Invalid move. Please try again.");
}
}
}
private String gameStatus(){
// Check rows and columns for a win
for (int i =0; i <3; i++){
if (board[i][0]== turn && board[i][1]== turn && board[i][2]== turn) return String.valueOf(turn);
if (board[0][i]== turn && board[1][i]== turn && board[2][i]== turn) return String.valueOf(turn);
}
// Check diagonals for a win
if (board[0][0]== turn && board[1][1]== turn && board[2][2]== turn) return String.valueOf(turn);
if (board[0][2]== turn && board[1][1]== turn && board[2][0]== turn) return String.valueOf(turn);
// Check for draw
boolean isDraw = true;
for (int i =0; i <3; i++){
for (int j =0; j <3; j++){
if (board[i][j]==''){
isDraw = false;
break;
}
}
}
return isDraw ? "Draw" : "Continue";
}
public void play(){
while (true){
printBoard();
getNextMove();
String status = gameStatus();
if (!status.equals("Continue")){
winner = status;
printBoard();
if (winner.equals("Draw")){
System.out.println("The game is a draw.");
} else {
System.out.println("Player "+ winner +" wins!");
}
break;
}
// Switch turns
turn =(turn =='X')?'O' : 'X';
}
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!