Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 05 / Topic 7 of 7

Putting it together: discount calculator

Real-world example: Asha's Store, Pune needs one discount calculator that handles a plain price, a percentage-off sale, a percentage-off sale stacked with a flat coupon, a whole basket of item prices, and a multi-year loyalty card — using everything from this part.

static final double GST_RATE = 0.18;

// Overload 1: price only, no discount, but GST still applies.
static double finalPrice(double price) {
    return withGst(price);
}

// Overload 2: a percentage discount, then GST.
static double finalPrice(double price, double percentOff) {
    double discounted = price - (price * percentOff / 100);
    return withGst(discounted);
}

// Overload 3: a percentage discount, then one flat coupon, then GST.
static double finalPrice(double price, double percentOff, String couponCode) {
    double discounted = price - (price * percentOff / 100);
    if ("SAVE100".equals(couponCode)) {
        discounted = Math.max(discounted - 100, 0);
    }
    return withGst(discounted);
}

static double withGst(double price) {
    return round2(price * (1 + GST_RATE));
}

// Varargs: any number of item prices in one basket.
static double totalBill(double... prices) {
    double total = 0;
    for (double price : prices) {
        total += price;
    }
    return round2(total);
}

// Recursive: apply percentOff again for each renewal year left.
static double loyaltyPrice(double price, double percentOff, int yearsLeft) {
    if (yearsLeft == 0) {               // base case
        return round2(price);
    }
    double afterOneYear = price - (price * percentOff / 100);
    return loyaltyPrice(afterOneYear, percentOff, yearsLeft - 1);
}

System.out.println(finalPrice(1000.0));                        // 1180.0
System.out.println(finalPrice(1000.0, 20.0));                  // 944.0
System.out.println(finalPrice(1000.0, 10.0, "SAVE100"));       // 944.0
System.out.println(totalBill(199.0, 349.0, 90.0, 60.0));        // 698.0
System.out.println(loyaltyPrice(1000.0, 5.0, 3));               // 857.38

finalPrice(1000.0, 20.0) and finalPrice(1000.0, 10.0, "SAVE100") land on the same ₹944.0 here, by coincidence of these particular numbers — one path is a straight 20% off, the other is 10% off plus a ₹100 coupon. Try different prices and you will see them diverge.

Full program: examples/06_discount_calculator.java.

Done here? The practice set for Part 5 — including the solutions — is on the part page.

Search the guide