In a tictactoe game, I need to search the rows and colums of a2D arrray (the gam
ID: 3617549 • Letter: I
Question
In a tictactoe game, I need to search the rows and colums of a2D arrray (the game board) for the winner. This is what I have, butI know there is a shorter way. Can someone help me find the easierway to do this? Thank you. if ((board[0][0] =='X') && (board [1][0] == 'X') && (board[2][0] =='X')){
System.out.println("X is the winner!congratulations!");
theWinner = true;
} else if((board [0][0] =='O') && (board [1][0] =='O') &&(board [2][0] =='O'))
{
System.out.println("O is the winner!Congratulations!");
theWinner = true;
} In a tictactoe game, I need to search the rows and colums of a2D arrray (the game board) for the winner. This is what I have, butI know there is a shorter way. Can someone help me find the easierway to do this? Thank you. if ((board[0][0] =='X') && (board [1][0] == 'X') && (board[2][0] =='X'))
{
System.out.println("X is the winner!congratulations!");
theWinner = true;
} else if((board [0][0] =='O') && (board [1][0] =='O') &&(board [2][0] =='O'))
{
System.out.println("O is the winner!Congratulations!");
theWinner = true;
}
Explanation / Answer
for(int r = 0; r < 3;r++) { char temp =board[r][0]; if(temp != 'O'&& temp != 'X') { continue; } theWinner =true; for(int c = 1; c< 3; r++) { if(board[r][c] !=temp) { theWinner= false; break; } } if(theWinner) { // a player haswon } }Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.