// TrianglePrinter.java // A solution to CS 10, assignment 4, part 2b, Fall 2008 // cmc, updated 11/1/08 /** A subclass of FigurePrinter that prints triangle figures. Separately stores a width (its height is proportional). */ public class TrianglePrinter extends FigurePrinter { private int width; /** Constructor assigns character, offset amount, and width. @param symbol the character symbol to represent the figure. @param offset the offset (leading spaces) from the left margin. @param width the width of the figure in terms of characters - minimum width is 3 (smaller widths are set to 3), and width must be a multiple of 3 (other values are set to the nearest multiple of 3). */ public TrianglePrinter(char symbol, int offset, int width) { super(symbol, offset); setWidth(width); } /** No-argument constructor sets symbol to '*', offset to 0, and width to 3. */ public TrianglePrinter() { this('*', 0, 3); } /** Accessor for the width of this figure. @return the width. */ public int getWidth() { return width; } /** Sets the width of this figure. @param newWidth the figure's width in terms of spaces. */ public void setWidth(int newWidth) { width = newWidth; if (width < 3) width = 3; int mod = width % 3; if (mod != 0) { if (mod == 1) width -= 1; else width += 1; } } /** Prints the triangle figure. */ public void print() { char symbol = getSymbol(); // print top line shift(); for (int i = 0; i < width; i++) System.out.print(symbol); System.out.println(); // print sides, keeping track of distance between last symbols int left = 0, between = width - 2, halfway = width / 2; while (left < halfway - 1) { ++left; between -= 2; shift(); spaces(left); System.out.print(symbol); spaces(between); System.out.println(symbol); } // print bottom symbol only if sides have not already met if (between > 0) { shift(); spaces( halfway ); System.out.println(symbol); } } /** Checks if this object is identical to the other object. @param other the other object. @return true if the other object is a TrianglePrinter and its symbol, offset and width all match the corresponding data for this object. */ public boolean equals(Object other) { if (!super.equals(other)) return false; TrianglePrinter o = (TrianglePrinter)other; return width == o.width; } }