Reputation: 81
I am currently a week into learning Java, and I am doing a tic tac toe game. Almost everything is perfect, except for the fact that I don't know how to change 1's and 2's into X's and O's. My professor told us that we cannot change the main method. 0 represents a space, 1 represents an X, and 2 represents an O.
public static void printBoard(int[][] board) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 2) {
System.out.print(board[i][j] );
} else {
System.out.print(board[i][j] + " |");
}
}
}
}
Upvotes: 0
Views: 496
Reputation: 1106
One possibility is to create a method which converts a number to the character it represents, like below:
public static char toText(int num) {
switch (num) {
case 0: return ' ';
case 1: return 'X';
case 2: return 'O';
default: return '?';
}
}
And then you can use this method when printing your board. This would avoid having to change the way you internally represent your board:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (j == 2) {
System.out.print(toText(board[i][j]) );
} else {
System.out.print(toText(board[i][j]) + " |");
}
}
Upvotes: 2