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