I'm a beginner in programming and I'm making a simple game similar to Tic-Tac-Toe. We have a square game field (2D array) with random size of it's side. It may look like:
[ ] [ ] [ ]
[ ] [ ] [ ]
[ ] [ ] [ ]
Here is one of the methods to check out the matches for rows:
boolean checkHorizontal(String[][] field) {
boolean valid = true;
for (int i = 0; i < field.length; i++) {
for (int j = 1; j < field[i].length; j++) {
if (!field[i][0].equals(field[i][j]) && !field[i][0].equals("[ ]")) {
valid = false;
}
}
}
return valid;
}
And there is a problem in it. Method works correclty for usual cases, for example, like:
[ ] [ ] O
X X X
[ ] O [ ]
But if the game field is empty or the first column is empty, as following,
[ ] [ ] [ ] [ ] X [ ]
[ ] [ ] [ ] [ ] X [ ]
[ ] [ ] [ ] [ ] X [ ]
result of checkHorizontal(String[][] field)
is true
, but should be false
, because there are no matches in rows here, and I really don't know how to fix this.
Update. The answer of @David Choweller helped me. I altered his method a little bit, but in general it's the same thing:
boolean checkHorizontal(String[][] field) {
boolean valid = false;
for (int i = 0; i < field.length; i++) {
if (field[i][0].equals("[ ]")) {
continue;
}
int j;
for (j = 1; j < field[i].length; j++) {
if (!field[i][j].equals(field[i][0])) {
break;
}
}
if (j == field[i].length) {
valid = true;
}
}
return valid;
}
Assuming you want to return true if you find any horizontal row consisting of all Xs or all Os, and your empty field is the string "[ ]"
this should work:
boolean checkHorizontal(String[][] board) {
final String emptyCell = "[ ]";
for (int row = 0; row < board.length; row++) {
String firstElementInRow = board[row][0];
if (firstElementInRow.equals(emptyCell)) {
continue;
}
int column;
for (column=1; column < board[row].length; column++) {
if (!board[row][column].equals(firstElementInRow)) {
break;
}
}
if (column==board[row].length) {
return true;
}
}
return false;
}