Scribbles with arrays |
Earlier we designed a program to draw scribbles. That program used a recursive data structure involving an interface, ScribbleIfc, and classes representing an empty scribble, EmptyScribble, and non-empty scribbles, Scribble.
We can also write a non-recursive version of scribble that uses arrays rather than recursion. Because there will be a single class representing all scribbles, empty and non-empty, we do not need an interface. The new Scribble class will contain an instance variable, scribbleLine, holding an array of lines composing the scribble, and instance variable, numScribbles, which represents the number of lines currently held in the scribble.
An important difference between this version and the recursive version is that we must determine the maximum number, MAX_SCRIBBLES, of lines that a scribble can contain. Once that size has been exceeded, new line segments can no longer be added.
The Scribbler class has two methods that the recursive version did not: addLine and moreRoom. The first is necessary because we no longer want to create a new scribble every time a new line segment is added. The second is necessary so that the program can determine whether or not there is room to add a new line.
The full program is available through this link
Notice that rather than putting the array as an instance variable of the Scribbler class, we made it an instance variable of a separate Scribble class and provided associated methods for accessing it. This is the preferred way of writing programs that use arrays as we want to think of dealing not with the array itself, but instead with what the array represents. By including method names that make sense for the intended use of the array (e.g., contains for a scribble), we make it easier to program the problem. Among other things, you can see that the Scribbler class in this case looks very similar to the Scribbler class for the recursive case.
Scribbles with arrays |