There does not appear to be any code in what you posted that would cause a StackOverflowError (unless you're doing something really weird in printStatus
). The error causing that must be somewhere else in your code. So, unfortunately, unless you post more code, I can't help.
However, here are two things I noticed you could use some improvement on. First, (the way you're implementing this) you do not need nested for
loops. The loops beginning with for (int j = 0; j < 1; j++) {
, and with for (int i = 0; i < 1; i++) {
, are not necessary, and they cause errors, as they produce checks where only two boxes are checked, instead of three in a row. You can simplify them by simply eliminating those loops. (I also modified your if
statement, see below for more detail).
//Checks for winner by rows
for (int i = 0; i < 3; i++) {
if (board[i][j] == board[i][0 + 1] && board[i][j] == board[i][0 + 2]) { //Check if one player has matched a row
if (board[i][j] == 'X') { //Then check which player won
printStatus(1);
}
else{
printStatus(2);
}
return Status.WIN;
} else {
return Status.CONTINUE;
}
}
You can also simplify your if statement by only checking for whether X
or 0
occupy a space, after you have figured out someone won. So, for example, instead of doing
if (board[0][0] == 'X') {
if (board[0][0] == board[1][1] && board[0][0] == board[2][2]) {
printStatus(1);
}
//More code here
}
else if (board[0][0] == 'O') {
if (board[0][0] == board[1][1] && board[0][0] == board[2][2]) {
printStatus(1);
}
//More code here
}
You can simply the code by changing it to:
if (board[0][0] == board[1][1] && board[0][0] == board[2][2]) { //Check if first diagonal is complete
if (board[0][0] == 'X') { //Check who won
printStatus(1);
}
else{
printStatus(1);
}
return Status.WIN;
} else {
return Status.CONTINUE;
}
In this way, the statement if (board[0][0] == board[1][1] && board[0][0] == board[2][2])
is only executed once, and the second statement, if (board[0][0] == 'X')
, is only executed if someone has won the diagonal. In your implementation, the first check of if (board[0][0] == 'X')
will be run, then either the interior if statement, or it will execute the second player check, if (board[0][0] == 'O')
, then the interior one. In this way, your code will have to run between 2 and 3 different statements, whereas in mine, it's between 1 and 2 (with two only occurring when a player has won).