import java.util.Scanner; public class HelloWorld { static Scanner keyboard = new Scanner(System.in); static char[][] board; static char currentPlayerIcon; static boolean isGameOver; public static void main(String []args) { board = new char[3][3]; currentPlayerIcon = 'x'; ResetBoard(); PrintBoard(); while (isGameOver == false) { System.out.println("Player " + currentPlayerIcon + "'s turn, please select a row and column to place your icon."); System.out.println("Row: "); int row = keyboard.nextInt() - 1; System.out.println("Column: "); int col = keyboard.nextInt() - 1; while (PlaceIcon(row, col) == false) { System.out.println("Invalid Move!"); System.out.println("Player " + currentPlayerIcon + "'s turn, please select a row and column to place your icon."); System.out.println("Row: "); row = keyboard.nextInt() - 1; System.out.println("Column: "); col = keyboard.nextInt() - 1; } if (CheckForWin()) { System.out.println("Winner! Player " + currentPlayerIcon + " wins!"); isGameOver = true; } if (IsBoardFull()) { System.out.println("Game Over! No one wins!"); isGameOver = true; } ChangePlayer(); PrintBoard(); } } public static void ResetBoard() { for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { board[row][col] = '-'; } } } public static void PrintBoard() { System.out.println("-------------"); for (int row = 0; row < 3; row++) { System.out.print("| "); for (int col = 0; col < 3; col++) { System.out.print(board[row][col] + " | "); } System.out.println(); System.out.println("-------------"); } } public static boolean IsBoardFull() { for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { if (board[row][col] == '-') return false; } } return true; } public static boolean CheckForWin() { for (int i = 0; i < 3; i++) { //check the rows if (CompareSlots (board[i][0], board[i][1], board[i][2])) return true; //check the columns else if (CompareSlots (board[0][i], board[1][i], board[2][i])) return true; //check diagonals else if (CompareSlots (board[0][0], board[1][1], board[2][2]) || CompareSlots (board[0][2], board[1][1], board[2][0])) return true; } return false; } public static boolean CompareSlots(char c1, char c2, char c3) { return ((c1 != '-') && (c1 == c2) && (c1 == c3)); } public static void ChangePlayer() { if (currentPlayerIcon == 'x') currentPlayerIcon = 'o'; else currentPlayerIcon = 'x'; } public static boolean PlaceIcon(int row, int col) { if ((row >= 0) && (row < 3)) { if ((col >= 0) && (col < 3)) { if (board[row][col] == '-') { board[row][col] = currentPlayerIcon; return true; } } } return false; } }