{}
CODE VISUALIZER
Master DSA, Python and C with step-by-step code visualization.
See it in action
CODE VISUALIZER
Master DSA, Python and C with step-by-step code visualization.
See it in action
run-icon
Main.java
import java.util.Scanner; public class Main { private int turn; private char[][] board; public Main() { board = new char[3][3]; turn = 0; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { board[i][j] = '-'; } } } public void printBoard() { System.out.print(" 0 1 2\n"); for (int i = 0; i < 3; i++) { System.out.print(i + " "); for (int j = 0; j < 3; j++) { System.out.print(board[i][j] + " "); } System.out.println(); } } public boolean pickLocation(int row, int col) { return row >= 0 && row < 3 && col >= 0 && col < 3 && board[row][col] == '-'; } public void takeTurn(int row, int col) { if (pickLocation(row, col)) { board[row][col] = (turn % 2 == 0) ? 'X' : 'O'; turn++; } else { System.out.println("Invalid move. Try again."); } } public boolean checkRow() { for (int i = 0; i < 3; i++) { if (board[i][0] != '-' && board[i][0] == board[i][1] && board[i][1] == board[i][2]) { return true; } } return false; } public boolean checkCol() { for (int i = 0; i < 3; i++) { if (board[0][i] != '-' && board[0][i] == board[1][i] && board[1][i] == board[2][i]) { return true; } } return false; } public boolean checkDiag() { return (board[0][0] != '-' && board[0][0] == board[1][1] && board[1][1] == board[2][2]) || (board[0][2] != '-' && board[0][2] == board[1][1] && board[1][1] == board[2][0]); } public boolean checkWin() { return checkRow() || checkCol() || checkDiag(); } public int getTurn() { return turn; } public static void main(String[] args) { Main game = new Main(); Scanner scanner = new Scanner(System.in); boolean gameWon = false; int totalTurns = 0; final int maxTurns = 9; while (!gameWon && totalTurns < maxTurns) { game.printBoard(); int row, col; String player = (game.getTurn() % 2 == 0) ? "X" : "O"; while (true) { System.out.println("Player " + player + ", enter your move (row and column): "); row = scanner.nextInt(); col = scanner.nextInt(); if (game.pickLocation(row, col)) { game.takeTurn(row, col); totalTurns++; break; } else { System.out.println("Invalid move. Please try again."); } } if (game.checkWin()) { game.printBoard(); System.out.println("Player " + player + " wins!"); gameWon = true; } } if (!gameWon) { game.printBoard(); System.out.println("It's a tie!"); } scanner.close(); } }
Output