Java Tutorial
Java Project: Tic-Tac-Toe
A 3x3 board as a 2D array of strings. Place marks, print the grid, and detect a winner.
What you will build
Print a board, place two marks, and check a row for a winner.
Board and winner
Example
public class Main {
static void show(String[][] b) {
for (String[] row : b) {
System.out.println(String.join(" | ", row));
}
}
static String winner(String[][] b) {
for (int i = 0; i < 3; i++) {
if (!b[i][0].equals(" ") && b[i][0].equals(b[i][1]) && b[i][1].equals(b[i][2])) return b[i][0];
if (!b[0][i].equals(" ") && b[0][i].equals(b[1][i]) && b[1][i].equals(b[2][i])) return b[0][i];
}
return " ";
}
public static void main(String[] args) {
String[][] b = {{" ", " ", " "}, {" ", " ", " "}, {" ", " ", " "}};
b[0][0] = "X";
b[1][1] = "O";
b[0][1] = "X";
b[0][2] = "X";
show(b);
System.out.println("winner: " + winner(b));
}
}Practice
- Compile the complete program at
/java/try. - Change one input value and compile again.
- Replace a hardcoded number with
Scannerwhen you want typed input.