Java:算法 - Yoshi Island Tax Calculator

一道考继承注意事项的算法填充题,按要求编写TaxCalculator的子类完成构造器和方法

题目:

/**
* This class should calculate the tax on an item
* sold to somewhere on Yoshi's Island. On Yoshi's
* Island, the tax rate is 7% (0.07) plus a flat
* rate of one dollar (1.00) for every item that
* costs one hundred dollars (100.0) or more.
*
* You MUST extend TaxCalculator to get credit. You
* must use the taxRate variable in the superclass
* and call the super class constructor.
*
* You must also override the toString method to
* return
* YoshiIslandTaxCalculator[taxRate=0.07]
*
* This class must have a constructor with no arguments.
*/
public class YoshiIslandTaxCalculator extends TaxCalculator{

// YOUR CODE HERE
}

 class TaxCalculator{
   private double taxRate;

  public TaxCalculator(double taxRate)
  {
    this.taxRate = taxRate;
  }

  public double getTaxRate(){ return this.taxRate; }
  public void setTaxRate(double newRate){ this.taxRate = newRate; }

  /**
  * calculateTax. Return the tax on the dollar amount
  * in originalAmount.
  *
  * @param originalAmount the cost to tax
  * @return the tax on that amount
  */
  public double calculateTax(double originalAmount){
    return originalAmount * taxRate;
  }

  @Override
  public String toString(){
    return "TaxCalculator[taxRate=" + this.taxRate + "]";
  }
}

个人参考答案:

public class YoshiIslandTaxCalculator extends TaxCalculator{
  private final static double YOSHI_ISLAND_TAXRATE = 0.07;
  private final static double FLAT_TAX = 1.0;
  private final static double FLAT_TAX_MIN =100.0;
  public YoshiIslandTaxCalculator() {
    super(YOSHI_ISLAND_TAXRATE);
  }

  public YoshiIslandTaxCalculator(double taxRate){
    super(taxRate);
  }

  public static void main(String[] args){

    YoshiIslandTaxCalculator yTaxCalculator
    = new YoshiIslandTaxCalculator(YOSHI_ISLAND_TAXRATE);
	
    double taxTotal = yTaxCalculator.calculateTax(90);

    System.out.println("Your tax is: "+ taxTotal + " dollars"
    + yTaxCalculator.toString());
   }

  @Override
  public double calculateTax(double originalAmount){

      double flatTax = (int)(originalAmount/FLAT_TAX_MIN)*FLAT_TAX;
      double sumTax = flatTax
      + (double)Math.round(super.calculateTax(originalAmount)*100)/100;
      return sumTax;

    }
  @Override
  public String toString(){
    return "\npowered by YoshiIslandTaxCalculator[taxRate=" + this.getTaxRate() + "]";
  }


}

输出:

Your tax is: 6.3 dollars
powered by YoshiIslandTaxCalculator[taxRate=0.07]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值