Tic-Tac-Toe Judge

Lab Java Advanced 30 points

Read a 3×3 board of X, O and .. Print X wins, O wins, draw or in progress.

Input

Three lines.

Output

One line.

Example

Input

XXX
O.O
...

Output

X wins
Sample input available Sample output available
Editor
Java

Hints

Check 3 rows, 3 columns and 2 diagonals for each player.

Solution explanation

A helper method that answers one question ("does p win?") keeps main readable.

Show solution
import java.util.Scanner;

public class Main {
    static boolean wins(char[][] b, char p) {
        for (int i = 0; i < 3; i++) {
            if (b[i][0] == p && b[i][1] == p && b[i][2] == p) return true;
            if (b[0][i] == p && b[1][i] == p && b[2][i] == p) return true;
        }
        return (b[0][0] == p && b[1][1] == p && b[2][2] == p) || (b[0][2] == p && b[1][1] == p && b[2][0] == p);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        char[][] b = new char[3][];
        boolean empty = false;
        for (int i = 0; i < 3; i++) {
            b[i] = sc.next().toCharArray();
            for (char c : b[i]) if (c == '.') empty = true;
        }
        if (wins(b, 'X')) System.out.println("X wins");
        else if (wins(b, 'O')) System.out.println("O wins");
        else System.out.println(empty ? "in progress" : "draw");
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD