/**
 * A class that uses recursion to format a number in any base/radix
 * (in the interval [2, 6])
 *
 * This version uses an attribute to keep track of the result of
 * the recursion
 *
 * @author  Prof. David Bernstein, James Madison Unversity
 * @verions 2.0
 */
 public class RadixFormatter
 {
    private String       formatted;


    private final int    MAX_BASE    = 36;
    private final char[] DIGIT_TABLE = 
	 				{
					'0','1','2','3','4','5','6','7','8',
					'9','A','B','C','D','E','F','G','H',
					'I','J','K','L','M','N','O','P','Q',
					'R','S','T','U','V','W','X','Y','Z'
               };

    /**
     * Default Constructor
     */
     public RadixFormatter()
     {
			formatted = "";
     }

    /**
     * The "exposed" interface.  This function does
     * initialization and error-checking.
     *
     * @param n    The number to print
     * @param base The base to use
     * @return     The formatted String
     */
     public String formatInBase(int n, int base)
    	{
			if ((base <= 1) || (base > MAX_BASE)) 
			{
	  		  formatted = "Invalid base: "+base;
			} 
			else 
			{
	    		if (n < 0) 
	    		{
					formatted = "-";
					n = -n;
	    		}

	    		formatRecursively(n, base);
			} // end else

			return formatted;
  
    } // end RadixFormatter




    /**
     * The recursive function
     *
     * @param n    The number to print
     * @param base The base to use
     */
    private void formatRecursively(int n, int base)
    {
	if (n >= base) 
        {
	    formatRecursively(n/base, base);
	}

	formatted += DIGIT_TABLE[n % base];
    }
    
}
