Methods: Communicating with Objects
We communicate with objects using methods. Methods are executable code within each object, for which an interface has been established. Sometimes the interface is only for the object itself. Other times it is an interface accessible by other objects. This chapter discusses that topic in detail.
3.6 Flow of Control: Control Structures
We have been ignoring a couple of problems with the definition of the
OneRowNim class. One problem is that we would describe a One Row
Nim game as two players taking turns until there are no more sticks. An
object using OneRowNim would need a way to repeatedly execute a group
of statements. One command in Java that controls the repetition of a block
of statements is called a while loop. We will consider it later in this section.
A second problem is with the definition of takeSticks():
It is possible to call this method with an argument greater than 3 or less
than 1. The call game.takeSticks(5) will remove 5 sticks even though
the rules of One Row Nim say that you must remove 1, 2, or 3. While one
might assume that the user interface should prevent the user from breaking this rule, it is a far better design if it was dealt with in OneRowNim.
To do this we need a Java structure that executes different statements depending on whether the parameter is greater than 3, less than 1, or between 1 and 3. The Java if-else statement has this capability. A fuller treatment of control structures appears in Chapter 6, but in this section, we will
briefly introduce a couple of simple control structures. This will enable us
to write programs that take more interesting actions.