pricecalculations.java

来自「Java the UML Way 书中所有源码」· Java 代码 · 共 70 行

JAVA
70
字号
/*
 * PriceCalculations.java   E.L. 2001-08-10
 *
 * This program is calculating the price of a given amount (kilo) of merchandise.
 */

class Merchandise {
  private static final double VAT = 20.0;
  private static final double VATfactor = 1.0 + VAT / 100.0;

  private String merchandiseName;
  private int merchandiseNo;
  private double price; // price per kilo, without VAT

  public Merchandise(String initMerchandiseName,
            int initMerchandiseNo, double initPrice) {
    merchandiseName = initMerchandiseName;
    merchandiseNo = initMerchandiseNo;
    price = initPrice;
  }

  public Merchandise(String initMerchandiseName, int initMerchandiseNo) {
    merchandiseName = initMerchandiseName;
    merchandiseNo = initMerchandiseNo;
    price = 0.0;
  }

  public double getPriceWithoutVAT(double noKilo) {
    return price * noKilo;
  }

  public double getPriceWithVAT(double noKilo) {
    return price * noKilo * VATfactor;
  }

  public void setPrice(double newPrice) {
    price = newPrice;
  }
}


class PriceCalculations {
  public static void main(String[] args) {
    final double amount = 2.5;
    final double kiloPrice1 = 7.30;
    final double kiloPrice2 = 7.90;
    Merchandise aMerchandise = new Merchandise("Brie", 123, kiloPrice1);
    double price1 = aMerchandise.getPriceWithoutVAT(amount);
    double price2 = aMerchandise.getPriceWithVAT(amount);
    System.out.println("The price per kilo without VAT: " + kiloPrice1);
    System.out.println("The price for " + amount + " kilos is " + price1 + " without VAT");
    System.out.println("The price for " + amount + " kilos is " + price2 + " with VAT");

    aMerchandise.setPrice(kiloPrice2);
    System.out.println("New price per kilo without VAT: " + kiloPrice2);
    System.out.println("The price for " + amount + " kilos is "
        + aMerchandise.getPriceWithoutVAT(amount) + " without VAT");
    System.out.println("The price for " + amount + " kilos is "
        + aMerchandise.getPriceWithVAT(amount) + " with VAT");
  }
}

/* Example Run:
The price per kilo without VAT: 7.3
The price for 2.5 kilos is 18.25 without VAT
The price for 2.5 kilos is 21.9 with VAT
New price per kilo without VAT: 7.9
The price for 2.5 kilos is 19.75 without VAT
The price for 2.5 kilos is 23.7 with VAT
*/

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?