Java Reference
In-Depth Information
Table 2.10
Analysis of Different Height Figures
Dashes in
Spaces in
Dots in
Spaces in
Dots in
Subheight
drawLine
drawTop
drawTop
drawBottom
DrawBottom
3
6
line - 1
6 - 2 * line
3 - line
2 * (line - 1)
4
8
line - 1
8 - 2 * line
4 - line
2 * (line - 1)
the height is determined by the width and vice versa. Consequently, we only need to
introduce a single class constant. Let's use the height of the hourglass halves:
public static final int SUB_HEIGHT = 4;
We've called the constant
SUB_HEIGHT
rather than
HEIGHT
because it refers to the
height of each of the two halves, rather than the figure as a whole. Notice how we use
the underscore character to separate the different words in the name of the constant.
So, how do we modify the original program to incorporate this constant? We look
through the program for any magic numbers and insert the constant or an expression
involving the constant where appropriate. For example, both the
drawTop
and
drawBottom
methods have a
for
loop that executes 3 times to produce 3 lines of
output. We change this to 4 to produce 4 lines of output, and more generally, we
change it to
SUB_HEIGHT
to produce
SUB_HEIGHT
lines of output.
In other parts of the program we have to update our formulas for the number of
dashes, spaces, and dots. Sometimes we can use educated guesses to figure out how
to adjust such a formula to use the constant. If you can't guess a proper formula, you
can use the table technique to find the appropriate formula. Using this new output
with a subheight of 4, you can update the various formulas in the program. Table 2.10
shows the various formulas.
We then go through each formula and figure out how to replace it with a new formula
involving the constant. The number of dashes increases by 2 when the subheight
increases by 1, so we need a multiplier of 2. The expression
2 * SUB_HEIGHT
produces
the correct values. The number of spaces in
drawTop
does not change with the sub-
height, so the expression does not need to be altered. The number of dots in
drawTop
involves the number 6 for a subheight of 3 and the number 8 for a subheight of 4. Once
again we need a multiplier of 2, so we use the expression
2 * SUB_HEIGHT - 2 *
line
. The number of spaces in
drawBottom
involves the value 3 for a subheight of 3
and the value 4 for a subheight of 4, so the generalized expression is
SUB_HEIGHT -
line
. The number of dots in
drawBottom
does not change when subheight changes.
Here is the new version of the program with a class constant for the subheight. It
uses a
SUB_HEIGHT
value of
4
, but we could change this to
3
to produce the smaller
version or to some other value to produce yet another version of the figure.
1
public class
DrawFigure2 {
2
public static final int
SUB_HEIGHT = 4;
3
4
public static void
main(String[] args) {
5 drawLine();
Search WWH ::
Custom Search