Solution Review: Task V and VI
Let’s look at the solution to the problem in the previous lesson.
Task V: Implement the winning conditions
The task was to code the winning conditions to check for the winner.
Press + to interact
public static char winner(char[][] game_board) {//Check all the rowsfor(int i = 0; i < 3; i++) {if(game_board[i][0] == game_board[i][1] && game_board[i][1] == game_board[i][2] && game_board[i][0] != ' ') {return game_board[i][0];}}//Check each columnfor(int j = 0; j < 3; j++) {if(game_board[0][j] == game_board[1][j] && game_board[1][j] == game_board[2][j] && game_board[0][j] != ' ') {return game_board[0][j];}}//Check the diagonalsif(game_board[0][0] == game_board[1][1] && game_board[1][1] == game_board[2][2] && game_board[0][0] != ' ') {return game_board[0][0];}if(game_board[2][0] == game_board[1][1] && game_board[1][1] == game_board[0][2] && game_board[2][0] != ' ') {return game_board[2][0];}//Nobody has not won yetreturn ' ';}
-
Lines 4–8: We use a
for
loop to check if there are any three consecutivex
...
Get hands-on with 1400+ tech skills courses.