Java Reference
In-Depth Information
Table 2.9
Analysis of Figure
Line
Spaces
Dots
Spaces
1
0
4
0
2
1
2
1
3
2
0
2
The pseudocode for the top half of the hourglass is easily translated into a static
method called
drawTop
. A similar solution exists for the bottom half of the hour-
glass. Put together, the program looks like this:
1
public class
DrawFigure {
2
public static void
main(String[] args) {
3 drawLine();
4 drawTop();
5 drawBottom();
6 drawLine();
7 }
8
9 // produces a solid line
10
public static void
drawLine() {
11 System.out.print("+");
12
for
(
int
i = 1; i <= 6; i++) {
13 System.out.print("-");
14 }
15 System.out.println("+");
16 }
17
18 // produces the top half of the hourglass figure
19
public static void
drawTop() {
20
for
(
int
line = 1; line <= 3; line++) {
21 System.out.print("|");
22
for
(
int
i = 1; i <= (line - 1); i++) {
23 System.out.print(" ");
24 }
25 System.out.print("\\");
26
for
(
int
i = 1; i <= (6 - 2 * line); i++) {
27 System.out.print(".");
28 }
29 System.out.print("/");
30
for
(
int
i = 1; i <= (line - 1); i++) {
31 System.out.print(" ");
32 }
Search WWH ::
Custom Search