/**
 * A class that uses recursion to format a number in any base/radix
 * (in the interval [2, 36])
 *
 * This version uses an attribute to keep track of the base.
 *
 * @author  Prof. David Bernstein, James Madison Unversity
 * @verions 2.0
 */
public class RadixFormatter
{
    private final int      MAX_BASE    = 36;
    private final String[] 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"
                                         };
    private int base;
    

    /**
     * Constructor
     */
    public RadixFormatter(int base)
    {
        this.base = base;
    }

    /**
     * The "exposed" interface.  This function does
     * initialization and error-checking.
     *
     * @param n    The number to print
     * @return     The formatted String
     */
    public String formatInBase(int n)
    {
        String formatted = "";
        
	if ((base <= 1) || (base > MAX_BASE)) 
	{
	    formatted = "Invalid base: "+base;
	} 
	else 
	{
	    if (n < 0) 
	    {
		formatted = "-";
		n = -n;
	    }
            
	    formatted += formatRecursively(n);
	}

	return formatted;
    }




    /**
     * The recursive function
     *
     * @param n    The number to print
     */
    private String formatRecursively(int n)
    {
        // Base Case
        if (n < base) return DIGIT_TABLE[n % base];
        
        // Refinement
        return formatRecursively(n/base) + DIGIT_TABLE[n % base];
    }
    
}
