CS 051 | Fall 2012 |
See class demo ArrayScribbler
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.
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.
Line[] scribbleLine = new Line[MaxVals]; ... for (int i = 0; i < MaxVals; i++) { scribbleLine[i].move(xOffset,yOffset); }
or equivalently
for (Line line:scribbleLine) { line.move(xOffset,yOffset); }
Note that this only works if the array is full, otherwise you will get a NullPointerException
when you send the move message to unfilled slots. This new for construct "iterates" through all
of the elements in the array from 0 to MaxVals - 1.
See class demos Drawing Program and Array List Scribbler
Notice that in each case we do not need to keep track of the number of elements in the ArrayList
as the data structure keeps track of it itself. Notice also in the first program that we can just
send the delete message to an array list with the index and it will automatically shift
everything over to fill the gap. While we only add at the end of the array here, it will also
allow us to add something in th middle and shove all of the old elements over to make space.
The code in the ArrayListScribbler controller class is identical (except for the
check for more room) to the controller code from ArrayScribbler. This is the
result of our design decision to create a separate class for our Scribble implementation.