Skip to content
Tutorials Center
My learning

Topics

Lesson 189 of 201 ยท Projects

Project: Supermarket Billing System

Build a Java supermarket billing system with a product catalog, a cart, sealed discount rules, tax on taxable items and an aligned receipt, all with exact BigDecimal money.

A supermarket till looks simple: scan items, print a total. Underneath it is a nice little design problem. Prices must be exact, so there can be no floating-point money. Discounts come in several shapes, and new promotions appear every week. The receipt has to line up in neat columns whatever the numbers are, and a mistyped barcode must never crash the register.

In this project you will build the billing engine in three stages: a catalog and a cart with exact arithmetic, then discount rules modeled as a sealed interface, and finally tax and a formatted receipt. You'll use records, maps, BigDecimal and String.format. The product names and prices are invented sample data.

Design

Four small types are enough:

Type Responsibility
Product One item in the catalog: SKU (barcode), name, price, whether tax applies
Line A product and a quantity; knows its own total
Discount A rule that, given a line, says how much money to take off
Cart Collects lines, merges repeated scans of the same SKU, rejects bad input

Two rules shape everything else. Money is always BigDecimal built from strings, never a double. And each discount is its own record, so adding a promotion means adding a type, not editing a giant if chain.

Stage 1: catalog, cart and exact totals

Java Stage 1: lines and subtotal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

BigDecimal.valueOf(qty) converts the quantity exactly, and multiply keeps the scale (the digits after the point) honest: 1.29 * 3 is 3.87. The last two lines show what you avoid: 0.10 * 3 in doubles is 0.30000000000000004, while BigDecimal gives exactly 0.30. A till that is off by a fraction of a cent on every item will eventually be off by real money.

The catalog is a LinkedHashMap keyed by SKU, so a scan is one lookup and iteration keeps the order the products were added.

Stage 2: discount rules as a sealed interface

Supermarkets run many kinds of promotion. Three common ones:

  • Percent off: 15% off coffee.
  • Buy N, get one free: buy two milks, get the third free.
  • Bulk price: four or more loaves at a lower unit price.

Each one answers the same question, "how many dollars does this line save?", with different logic. That is exactly what an interface is for. Making it sealed lists every kind of rule in one place, so a switch over a Discount is checked by the compiler for completeness.

Java Stage 2: three kinds of discount

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check the numbers by hand. Seven milks with "buy 2 get 1 free" is 7 / 3 = 2 free items, so the saving is 2 * 1.29 = 2.58. Two coffees cost 17.80, and 15% of that is 2.67. The divide(100, 2, HALF_UP) call fixes the scale and the rounding at the same time, which is mandatory because BigDecimal.divide otherwise throws on a non-terminating result. Four loaves drop from 2.49 to 2.00 each, saving 1.96. The single loaf does not qualify, so nothing is printed for it.

Integer division in line.qty() / (n + 1) is the whole trick behind "buy N get one free": every complete group of n + 1 items earns one free item and the remainder pays full price.

Which rule should win when two rules match one product? Real tills pick the best deal for the customer or follow a fixed priority, and they never stack by accident. In the final stage we take the first matching rule, so the order of the rules list is the priority order.

Stage 3: the cart, tax and the receipt

Now put it all together. The Cart validates input and merges repeated scans (scanning milk twice should produce one line with quantity 2, not two lines). Tax applies only to taxable products, and it applies to the price after discounts. The receipt pads the left and right parts of each row so the money column lines up at the right edge.

Java Stage 3: the complete billing system

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A few details worth studying:

  • lines.merge(...) inserts the new line, or combines it with the existing one through the lambda. It is the idiomatic way to "add to a counter" in a map.
  • row(left, right) computes the padding from the real string lengths, so the right column is flush whatever the text. Math.max(1, pad) keeps at least one space if a name is very long. For truly long names you would truncate with substring.
  • %,.2f is a String.format pattern: thousands separators and exactly two decimals. The espresso machine prints as 1,250.00.
  • Tax is computed once on the taxable total, then rounded once. Rounding tax per line is a different policy and can differ by a cent. Whatever you choose, apply it consistently and document it, because auditors will recompute it.
  • Errors are exceptions with clear messages. The Cart refuses an unknown SKU or a non-positive quantity before any state changes, so a bad scan cannot corrupt the bill. See throwing exceptions.

Design notes

  • A sealed interface means a new promotion is a new record plus one extra line in the permits clause. Every switch over Discount that does not cover it stops compiling, which is exactly the safety net you want.
  • Keeping Line.total() and Discount.amount() free of side effects makes them trivial to unit test: build a line, call the method, compare with assertEquals.
  • The receipt printer both calculates and prints. In a larger program you would split it: a Bill record holding subtotal, savings, tax and total, produced by one method and rendered by another, so the same bill can go to a printer, a screen or an email.

Ideas to extend it

  1. Read the catalog from a text file (sku;name;price;taxable) with Files.readAllLines.
  2. Add a "best deal wins" strategy: compute every matching discount and pick the largest instead of the first.
  3. Support a loyalty card with a flat percentage off the whole basket after line discounts.
  4. Print the date with java.time and a running receipt number.
  5. Handle currencies and rounding policies like the Currency Converter.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is every price in this project built with new BigDecimal("1.29") instead of new BigDecimal(1.29)?

    1.29 as a double is slightly off in binary. new BigDecimal(1.29) preserves that long inexact expansion, while new BigDecimal("1.29") is exactly 1.29.
  2. 2. A customer buys 7 milks with the rule "buy 2, get 1 free". How many are free?

    Every complete group of n + 1 = 3 items earns one free item. 7 / 3 is 2 with integer division, and the leftover item pays full price.
  3. 3. What does making Discount a sealed interface buy you here?

    A sealed hierarchy is closed. Adding a new permitted record makes every switch that forgot it a compile error instead of a silent bug.
  4. 4. Why does Cart.add use lines.merge(sku, newLine, combiner)?

    merge puts the value if the key is absent and otherwise calls the function with the old and new values, so repeated scans produce one line with a larger quantity.

Summary

  • Build money from strings and keep it in BigDecimal; round once, with an explicit scale and RoundingMode.
  • Model each promotion as its own record behind a sealed interface; the compiler then guards every switch over the rule types.
  • A Cart validates input up front and uses Map.merge so repeated scans combine into one line.
  • Compute padding from real string lengths to keep receipt columns aligned, and format money with %,.2f.
  • Decide tax and rounding policies once, apply them consistently, and keep calculation separate from printing as the program grows.

Next: Project: Word Counter, where you'll count word frequencies with streams and groupingBy.