Page 746 - Introduction to Programming with Java: A Problem Solving Approach
P. 746
712 Chapter 17 GUI Programming—Component Layout, Additional GUI Components
Yikes! That’s a lot of for loops! Is there a better way? How about taking the opposite approach and us- ing no for loops? Use one big if statement like this:
if (btns[0][0]
(btns[1][0]
...
(btns[0][2]
return true
else
return false
end-if
= X && btns[0][1] = X && btns[0][2] = X) ||
= X && btns[1][1] = X && btns[1][2] = X) ||
= X && btns[1][1] = X && btns[2][0] = X)
That works fine, but if you’re bothered by the length of the if condition (eight lines long), you might want to try the following. Use one for loop for all the rows, one for loop for all the columns, and one if state- ment for the two diagonals:
for (i=0; i<3; i++)
if (btns[i][0] = X && btns[i][1] = X && btns[i][2] = X)
return true
end-if
end-for
for (j=0; j<3; j++)
if (btns[0][j] = X && btns[1][j] = X && btns[2][j] = X)
return true
end-if
end-for
Apago PDF Enhancer
if (btns[0][0] = X && btns[1][1] = X && btns[2][2] = X) ||
(btns[0][2] = X && btns[1][1] = X && btns[2][0] = X)
return true
end-if
return false
Of the three solutions, we prefer the last one because we feel its code is the most understandable.
To make the tic-tac-toe program more “real world,” you’d probably want to provide additional function- ality. In particular, you’d want to check for a “cat’s game,” which is when the board is filled and no one has
won. You’re asked to implement that functionality in one of the chapter’s projects.
17.8 Embedded Layout Managers
Suppose you’d like to implement this math-calculator window: