Answer:
import java.util.*;
public class tictactoe{
//array to store values inserted in the bord
static char[][] board = {{' ',' ',' '},{' ',' ',' '},{' ',' ',' '}};
//method to display board
public static void display(){
System.out.println("-------------");
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print("|");
if(board[i][j] != ' ')
System.out.print(board[i][j]);
}
System.out.println("|");
}
System.out.println("-------------");
}
//method for player1 to make choice
public static void player1(){
Scanner in = new Scanner(System.in);
System.out.print("Enter a row for player X: ");
int row = in.nextInt();
System.out.print("Enter a column for player X: ");
int col = in.nextInt();
//if the value are not valid and not between 0-2
if(row > 2 || row < 0 || col > 2 || col < 0){
System.out.println("Invalid Choice");
player1();
}
//if selected position is empty
else if(board[row][col] == ' '){
board[row][col] = 'X';
check('X',row,col);
player2();
}
//if selected position is not empty
else{
System.out.println("Already filed, Enter another choice");
player1();
}
}
//method for player2 to make choice
public static void player2(){
Scanner in = new Scanner(System.in);
System.out.print("Enter a row for player O: ");
int row = in.nextInt();
System.out.print("Enter a column for player O: ");
int col = in.nextInt();
//if the value are not valid and not between 0-2
if(row > 2 || row < 0 || col > 2 || col < 0){
System.out.println("Invalid Choice");
player2();
}
//if selected position is empty
else if(board[row][col] == ' '){
board[row][col] = 'O';
check(')',row,col);
player1();
}
//if selected position is not empty
else{
System.out.println("Already filed, Enter another choice");
player2();
}
}
//method to check whether a player has won
public static void check(char s, int row, int col){
display();
//check row has same 3 values
int count = 0;
for(int i=0;i<3;i++){
if(board[row][i] == s)
count++;
}
if(count == 3){
System.out.println(s + " player won");
System.exit(0);
}
//checking column has same 3 values
count = 0;
for(int i=0;i<3;i++){
if(board[i][col] == s)
count++;
}
if(count == 3){
System.out.println(s + " player won");
System.exit(0);
}
//checking first diagonal has same 3 values
count = 0;
for(int i=0;i<3;i++){
if(board[i][i] == s)
count++;
}
if(count == 3){
System.out.println(s + " player won");
System.exit(0);
}
//checking second diagonal has same 3 values
count = 0;
for(int i=0;i<3;i++){
if(board[i][2-i] == s)
count++;
}
if(count == 3){
System.out.println(s + " player won");
System.exit(0);
}
//checking whether all places are filled
count = 0;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
if(board[i][j] == ' ')
count++;
if(count == 0){
System.out.println("Game tied");
System.exit(0);
}
}
public static void main(String[] args){
display();
player1();
}
}
Explanation: