Java:繼承類演算法題,Yoshi Island Tax Calculator
阿新 • • 發佈:2018-12-13
一道考繼承注意事項的演算法填充題,按要求編寫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]