Respuesta :
Answer and Explanation:
Here is the code for the question with output.
public interface NumberFormatter {
public String format(int n);
}
class DefaultFormatter implements NumberFormatter
{
public String format(int n)
{
return String.valueOf(n);
}
}
class DecimalFormatter implements NumberFormatter
{
public String format(int n)
{
return String.format("%,d",n); //formats the number by putting comma for 3 digits
}
}
class AccountingFormatter implements NumberFormatter
{
public String format(int n)
{
return String.format("(%d)",n);
}
}
class BaseFormatter implements NumberFormatter
{
int base;
public BaseFormatter(int b)
{
base = b;
if(base < 2 || base > 36) //if values out of range 2-36 inclusive are given, set default to 2
base = 2;
}
public String format(int n)
{
return Integer.toString(n, base);
}
int getBase()
{
return base;
}
}
public class TestNumberFormatter {
private static void print(int n, NumberFormatter formatter)
{
String s = String.format("%15s",formatter.format(n));
System.out.print(s);
}
public static void main(String[] args) {
int numbers[]= {100,55555,1000000,35,5};
DefaultFormatter defFmt = new DefaultFormatter();
DecimalFormatter deciFmt = new DecimalFormatter();
AccountingFormatter accFmt = new AccountingFormatter();
BaseFormatter baseFmt=new BaseFormatter(16) ; //base 16
String s;
System.out.println("\tDefault \t Decimal \tAccounting \t Base("+baseFmt.getBase()+")");
for(int i = 0; i < numbers.length; i++)
{
print(numbers[i], defFmt);
print(numbers[i], deciFmt);
print(numbers[i], accFmt);
print(numbers[i], baseFmt);
System.out.println();//new line
}
}
}
output
Default Decimal Accounting Base(16)
100 100 (100) 64
55555 55,555 (55555) d903
1000000 1,000,000 (1000000) f4240
35 35 (35) 23
5 5 (5) 5