Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class Exercise7_9 {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- String[][] choices = { { " ", " ", " " }, { " ", " ", " " }, { " ", " ", " " } };
- String currentPlayer = "X";
- String winner = "";
- int row, column;
- while (true) {
- System.out.println("-------------");
- System.out.println("| " + choices[0][0] + " | " + choices[0][1] + " | " + choices[0][2] + " |");
- System.out.println("-------------");
- System.out.println("| " + choices[1][0] + " | " + choices[1][1] + " | " + choices[1][2] + " |");
- System.out.println("-------------");
- System.out.println("| " + choices[2][0] + " | " + choices[2][1] + " | " + choices[2][2] + " |");
- System.out.println("-------------");
- if (winner != "") {
- System.out.println(winner + " player won");
- break;
- }
- System.out.print("Enter a row (0, 1, or 2) for player " + currentPlayer + ": ");
- row = in.nextInt();
- System.out.print("Enter a column (0, 1, or 2) for player " + currentPlayer + ": ");
- column = in.nextInt();
- if ((row <= 2 && row >= 0) && (column <= 2 && column >= 0) && (choices[row][column] == " ")) {
- choices[row][column] = currentPlayer;
- } else {
- System.out.println("Enter valid place");
- continue;
- }
- winner = Exercise7_9.winnerCheck(choices, currentPlayer);
- currentPlayer = (currentPlayer == "X") ? "O" : "X";
- }
- }
- public static String winnerCheck(String[][] choices, String currentPlayer) {
- String conditions[] = new String[8];
- conditions[0] = choices[0][0] + choices[0][1] + choices[0][2];
- conditions[1] = choices[1][0] + choices[1][1] + choices[1][2];
- conditions[2] = choices[2][0] + choices[2][1] + choices[2][2];
- conditions[3] = choices[0][0] + choices[1][0] + choices[2][0];
- conditions[4] = choices[0][1] + choices[1][1] + choices[2][1];
- conditions[5] = choices[0][2] + choices[1][2] + choices[2][2];
- conditions[6] = choices[0][0] + choices[1][1] + choices[2][2];
- conditions[7] = choices[0][2] + choices[1][1] + choices[2][0];
- for (String condition : conditions) {
- if (condition.equals("XXX") || condition.equals("OOO")) {
- return currentPlayer;
- }
- }
- return "";
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement