package poly.visitor; import poly.*; public class ToString implements IVisitor { // singleton pattern public static ToString Singleton = new ToString ( ); /** * Private Constructor for singleton pattern */ private ToString ( ) { } /** * Called with constant polynomials. The coefficient * could be anything including zero. Just return the * string value of the coefficient. * * @param poly the constant polynomial to print as a string * * @param input ignored parameter * * @return the string representing this polynomial */ public Object forConst ( ConstPoly poly, Object input ) { return Double.toString ( poly.getLeadCoef ( ) ); } /** * Called with non-constant polynomials. The coefficient * could be anything except zero. Return * coefficient x^ exponent and toStringHelp of rest * * @param poly the non-constant polynomial to print as a string * * @param input ignored parameter * * @return the string representing this polynomial */ public Object forNonConst ( NonConstPoly poly, Object input ) { return ( poly.getLeadCoef ( ) + "x^" + poly.getDegree ( ) + poly.getLowerPoly ( ).execute ( ToStringHelper.Singleton, null ) ); } } class ToStringHelper implements IVisitor { // singleton pattern public static ToStringHelper Singleton = new ToStringHelper ( ); /** * Private Constructor for singleton pattern */ private ToStringHelper ( ) { } /** * Called with constant polynomials. The coefficient * could be anything including zero. Check to see if it's * zero. If so, don't print anything. Otherwise, print * "+ coefficient" * * @param poly the constant polynomial to print as a string * * @param input ignored parameter * * @return the string representing this polynomial */ public Object forConst ( ConstPoly poly, Object input ) { double coef = poly.getLeadCoef ( ); if ( coef == 0.0 ) { return ""; } else if ( coef < 0 ) { return ( " - " + -coef ); } else { return ( " + " + coef ); } } /** * Called with non-constant polynomials. The coefficient * could be anything except zero. Return * "+ coefficient x^ exponent" and toStringHelp of rest * * @param poly the non-constant polynomial to print as a string * * @param input ignored parameter * * @return the string representing this polynomial */ public Object forNonConst ( NonConstPoly poly, Object input ) { double coef = poly.getLeadCoef ( ); String lowerString = "x^" + poly.getDegree ( ) + poly.getLowerPoly ( ).execute ( this, null ); return coef < 0? " - " + -coef + lowerString: " + " + coef + lowerString; } }