Advertisement
PadmaJS

Exercise 7.9

Sep 30th, 2022
946
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Erlang 2.33 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Exercise7_9 {
  4.   public static void main(String[] args) {
  5.     Scanner in = new Scanner(System.in);
  6.  
  7.     String[][] choices = { { " ", " ", " " }, { " ", " ", " " }, { " ", " ", " " } };
  8.     String currentPlayer = "X";
  9.     String winner = "";
  10.     int row, column;
  11.     while (true) {
  12.       System.out.println("-------------");
  13.       System.out.println("| " + choices[0][0] + " | " + choices[0][1] + " | " + choices[0][2] + " |");
  14.       System.out.println("-------------");
  15.       System.out.println("| " + choices[1][0] + " | " + choices[1][1] + " | " + choices[1][2] + " |");
  16.       System.out.println("-------------");
  17.       System.out.println("| " + choices[2][0] + " | " + choices[2][1] + " | " + choices[2][2] + " |");
  18.       System.out.println("-------------");
  19.       if (winner != "") {
  20.         System.out.println(winner + " player won");
  21.         break;
  22.       }
  23.       System.out.print("Enter a row (0, 1, or 2) for player " + currentPlayer + ": ");
  24.       row = in.nextInt();
  25.       System.out.print("Enter a column (0, 1, or 2) for player " + currentPlayer + ": ");
  26.       column = in.nextInt();
  27.       if ((row <= 2 && row >= 0) && (column <= 2 && column >= 0) && (choices[row][column] == " ")) {
  28.         choices[row][column] = currentPlayer;
  29.       } else {
  30.         System.out.println("Enter valid place");
  31.         continue;
  32.       }
  33.       winner = Exercise7_9.winnerCheck(choices, currentPlayer);
  34.       currentPlayer = (currentPlayer == "X") ? "O" : "X";
  35.     }
  36.   }
  37.  
  38.   public static String winnerCheck(String[][] choices, String currentPlayer) {
  39.     String conditions[] = new String[8];
  40.     conditions[0] = choices[0][0] + choices[0][1] + choices[0][2];
  41.     conditions[1] = choices[1][0] + choices[1][1] + choices[1][2];
  42.     conditions[2] = choices[2][0] + choices[2][1] + choices[2][2];
  43.     conditions[3] = choices[0][0] + choices[1][0] + choices[2][0];
  44.     conditions[4] = choices[0][1] + choices[1][1] + choices[2][1];
  45.     conditions[5] = choices[0][2] + choices[1][2] + choices[2][2];
  46.     conditions[6] = choices[0][0] + choices[1][1] + choices[2][2];
  47.     conditions[7] = choices[0][2] + choices[1][1] + choices[2][0];
  48.     for (String condition : conditions) {
  49.       if (condition.equals("XXX") || condition.equals("OOO")) {
  50.         return currentPlayer;
  51.       }
  52.     }
  53.     return "";
  54.   }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement