Source of Triangle.java


  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 extends ShapeBasics implements TriangleInterface
 11: {
 12:     private int base;
 13: 
 14:     public Triangle( )
 15:     {
 16:         super( );
 17:         base = 0;
 18:     }
 19: 
 20:     public Triangle(int theOffset, int theBase)
 21:     {
 22:         super(theOffset);
 23:         base = theBase;
 24:     }
 25: 
 26:     /** Precondition: newBase is odd. */
 27:         public void set(int newBase)
 28:     {
 29:         base = newBase;
 30:     }
 31: 
 32:     /** Draws the shape at current line. */
 33:     public void drawHere( )
 34:     {
 35:         drawTop( );
 36:         drawBase( );
 37:     }
 38: 
 39:     private void drawBase( )
 40:     {
 41:         skipSpaces(getOffset( ));
 42:         for (int count = 0; count < base; count++)
 43:             System.out.print('*');
 44:          System.out.println( );
 45:     }
 46: 
 47:     private void drawTop( )
 48:     {
 49:         //startOfLine == number of spaces to the 
 50:         //first '*' on a line. Initially set to the  
 51:         //number of spaces before the topmost '*'.
 52:                 int startOfLine = getOffset( ) + base / 2;
 53:         skipSpaces(startOfLine);
 54:         System.out.println('*');//top '*'
 55:         int lineCount = base / 2 - 1; //Height above base
 56:                 
 57:         //insideWidth == number of spaces between the
 58:         //two '*'s on a line.
 59:         int insideWidth = 1;
 60:         for (int count = 0; count < lineCount; count++)
 61:         {
 62:             //Down one line, so the first '*' is one more
 63:             //space to the left.
 64:             startOfLine--;
 65:             skipSpaces(startOfLine);
 66:             System.out.print('*');
 67:             skipSpaces(insideWidth);
 68:             System.out.println('*');
 69:                         
 70:             //Down one line, so the inside is 2 spaces wider.
 71:             insideWidth = insideWidth + 2;
 72:         }
 73:     }
 74: 
 75:     private static void skipSpaces(int number)
 76:     {
 77:         for (int count = 0; count < number; count++)
 78:             System.out.print(' ');
 79:     }
 80: }
 81: