public class DetectWin { public static void main(String[] args) { char[][] a = { {'O', 'O', 'X'}, {'X', 'X', 'X'}, {'O', ' ', 'O'} }; /* a.length is the number of rows. a[0].length is the number of columns in row 0. a[1].length is the number of columns in row 1. a[2].length is the number of columns in row 2. */ //Are there any winning columns? for (int col = 0; col < a[0].length; ++col) { int countX = 0, countO = 0; for (int row = 0; row < a.length; ++row) { if (a[row][col] == 'X') { ++countX; } else if (a[row][col] == 'O') { ++countO; } } if (countX == a.length) { System.out.println("Column " + col + " is all X's."); System.exit(0); } if (countO == a.length) { System.out.println("Column " + col + " is all O's."); System.exit(0); } } //Are there any winning rows? for (int row = 0; row < a.length; ++row) { int countX = 0, countO = 0; for (int col = 0; col < a[row].length; ++col) { if (a[row][col] == 'X') { ++countX; } else if (a[row][col] == 'O') { ++countO; } } if (countX == a[row].length) { System.out.println("Row " + row + " is all X's."); System.exit(0); } if (countO == a[row].length) { System.out.println("Row " + row + " is all O's."); System.exit(0); } } //Does the upper left to lower right diagonal win? int countX = 0, countO = 0; for (int i = 0; i < a.length; ++i) { if (a[i][i] == 'X') { ++countX; } else if (a[i][i] == 'O') { ++countO; } } if (countX == a.length) { System.out.println("Upper left to lower right diagonal " + "is all X's."); System.exit(0); } if (countO == a.length) { System.out.println("Upper left to lower right diagonal " + "is all O's."); System.exit(0); } //Didn't bother with other diagonal. System.out.println("Nobody won."); } }