For a project at University, I have to create a game of Tic Tac Toe.
I have this for
loop with if
statements to search through the 2D array of 3x3 size, and return if it's either X
or O
(enum). That results in showing which side has won the game.
However, the problem I have is that if the 2D array is not complete, as in if all the 9 boxes are not filled with X
or O
, the method shows a NullPointerException
.
Edit: I have to add that I require the empty grid to be null
as few other unit tests assume grid[][]
is initialized as null
.
Error:
Exception in thread "main" java.lang.NullPointerException
at TicTacToeImplementation.whoHasWon(TicTacToeImplementation.java:80)
at ApplicationRunner.main(ApplicationRunner.java:24)
Code:
public enum Symbol {
X, O
}
private Symbol winner;
public Symbol whoHasWon() {
for (Symbol xORo : Symbol.values()) {
if ((grid[0][0].equals(xORo) &&
grid[0][1].equals(xORo) &&
grid[0][2].equals(xORo))) {
winner = xORo;
isGameOver = true;
break;
} else if ((grid[1][0].equals(xORo) &&
grid[1][1].equals(xORo) &&
grid[1][2].equals(xORo))) {
winner = xORo;
isGameOver = true;
break;}
else if { //Code carries on to account for all 8 different ways of winning
} else {
isGameOver = true;
}
}
return winner;
}