Java Reference
In-Depth Information
33 System.out.println("|");
34 }
35 }
36
37 // produces the bottom half of the hourglass figure
38 public static void drawBottom() {
39 for ( int line = 1; line <= 3; line++) {
40 System.out.print("|");
41 for ( int i = 1; i <= (3 line); i++) {
42 System.out.print(" ");
43 }
44 System.out.print("/");
45 for ( int i = 1; i <= 2 * (line 1); i++) {
46 System.out.print(".");
47 }
48 System.out.print("\\");
49 for ( int i = 1; i <= (3 line); i++) {
50 System.out.print(" ");
51 }
52 System.out.println("|");
53 }
54 }
55 }
Adding a Class Constant
The DrawFigure program produces the desired output, but it is not very flexible.
What if we wanted to produce a similar figure of a different size? The original prob-
lem involved an hourglass figure that had three lines in the top half and three lines in
the bottom half. What if we wanted the following output, with four lines in the top
half and four lines in the bottom half?
+--------+
|\....../|
| \..../ |
| \../ |
| \/ |
| /\ |
| /..\ |
| /....\ |
|/......\|
+--------+
Obviously the program would be more useful if we could make it flexible enough
to produce either output. We do so by eliminating the magic numbers with the intro-
duction of a class constant. You might think that we need to introduce two constants—
one for the height and one for the width—but because of the regularity of this figure,
 
Search WWH ::




Custom Search