Commit 4a93a0b
committed
feat: Add CalculateDiscount class with variable argument discount calculator
WHAT the code does:
- Defines a `CalculateDiscount` class with method `calculateTotalWithDiscount(double... prices)`:
- Accepts a variable number of price values.
- Sums all the prices.
- Applies discounts based on total:
- `< 500` → 10% discount.
- `500–1000` → 5% discount.
- `> 1000` → no discount.
- Returns final discounted total.
- `main()` tests the method with three examples:
1. `(100, 150, 200)` → total `450`, 10% discount → `405.0`.
2. `(300, 250)` → total `550`, 5% discount → `522.5`.
3. `(600, 500)` → total `1100`, no discount → `1100.0`.
WHY this matters:
- Demonstrates **varargs (variable arguments)** in methods.
- Combines iteration, conditional logic, and return values.
- Simulates a real-world use case: applying discounts based on order total.
HOW it works:
1. Enhanced `for` loop calculates total sum.
2. Conditional logic (`if / else if / else`) applies correct discount tier.
3. Prints messages to explain discount applied.
4. Final discounted total is printed in each test case.
Tips & gotchas:
- Conditions are mutually exclusive, ensuring only one discount applies.
- Precision issues may arise with floating-point values; use `BigDecimal` for money in real applications.
- Current implementation applies discount once on total — not per item.
- Varargs allows flexibility: `calculateTotalWithDiscount()` can take any number of price inputs.
Use-cases:
- Educational demo of **varargs + conditional logic**.
- Useful for e-commerce or billing simulations.
- Good practice for method design with real-world scenarios.
- Can be extended with multiple discount strategies, loyalty points, or tax calculation.
Short key: class-calculatediscount-varargs-discount.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 0b30607 commit 4a93a0b
1 file changed
+22
-17
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
4 | | - | |
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
5 | 5 | | |
| 6 | + | |
| 7 | + | |
6 | 8 | | |
7 | 9 | | |
8 | 10 | | |
9 | 11 | | |
10 | | - | |
11 | | - | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
12 | 15 | | |
13 | | - | |
14 | | - | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
15 | 20 | | |
16 | 21 | | |
17 | | - | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
18 | 25 | | |
19 | 26 | | |
20 | 27 | | |
21 | 28 | | |
22 | | - | |
23 | 29 | | |
24 | 30 | | |
25 | 31 | | |
26 | | - | |
27 | | - | |
28 | | - | |
| 32 | + | |
| 33 | + | |
29 | 34 | | |
30 | | - | |
31 | | - | |
| 35 | + | |
| 36 | + | |
32 | 37 | | |
33 | | - | |
34 | | - | |
| 38 | + | |
| 39 | + | |
35 | 40 | | |
36 | 41 | | |
0 commit comments