public class Triangle
1: //Triangle.java
2:
3: /**
4: * Class for drawing triangles on the screen using keyboard
5: * characters. A triangle points up. Its size is determined
6: * by the length of its base, which must be an odd integer.
7: * Inherits getOffset, setOffset, and drawAt from the class
8: * ShapeBasics.
9: */
10: public class Triangle
11: extends ShapeBasics
12: implements TriangleInterface
13: {
14: private int base;
15:
16: public Triangle()
17: {
18: super();
19: base = 0;
20: }
21:
22: public Triangle
23: (
24: int theOffset,
25: int theBase
26: )
27: {
28: super(theOffset);
29: base = theBase;
30: }
31:
32: /**
33: * Precondition: newBase is odd.
34: */
35: public void set
36: (
37: int newBase
38: )
39: {
40: base = newBase;
41: }
42:
43: /**
44: * Draws the shape at current line.
45: */
46: public void drawHere()
47: {
48: drawTop();
49: drawBase();
50: }
51:
52: private void drawBase()
53: {
54: skipSpaces(getOffset());
55: for (int count = 0; count < base; count++)
56: System.out.print('*');
57: System.out.println();
58: }
59:
60: private void drawTop()
61: {
62: //startOfLine == number of spaces to the
63: //first '*' on a line. Initially set to the
64: //number of spaces before the topmost '*'.
65: int startOfLine = getOffset() + base / 2;
66: skipSpaces(startOfLine);
67: System.out.println('*');//top '*'
68: int lineCount = base / 2 - 1; //Height above base
69:
70: //insideWidth == number of spaces between the
71: //two '*'s on a line.
72: int insideWidth = 1;
73: for (int count = 0; count < lineCount; count++)
74: {
75: //Down one line, so the first '*' is one more
76: //space to the left.
77: startOfLine--;
78: skipSpaces(startOfLine);
79: System.out.print('*');
80: skipSpaces(insideWidth);
81: System.out.println('*');
82:
83: //Down one line, so the inside is 2 spaces wider.
84: insideWidth = insideWidth + 2;
85: }
86: }
87:
88: private static void skipSpaces
89: (
90: int number
91: )
92: {
93: for (int count = 0; count < number; count++)
94: System.out.print(' ');
95: }
96: }