Consider an interface p ublic interface NumberFormatter { String format (in n); } Provide four classes that implement this interface. A DefaultFormatter formats an integer in the usual way. A DecimalSeparatorFormatter formats an integer with decimal separators ; for example, one million as 1,000,000. An AccountingFor matter formats negative numbers with parenthesis; for example, - 1 as (1). A BaseFormatter formats the number as base n, where n is any number between 2 and 36 that is provided in the constructor.

Write a method that takes an array of integers and a NumberFormatter object and prints each number on a separate line, formatted with the given formatter. The numbers should be right aligned. Provide a test class th at shows the program working with an array of numbers.

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

ACCESS MORE
EDU ACCESS