Start learning free

LESSON 190 OF 671 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V5 in Java: Coupon Codes with a HashMap

Practice Read the full explanation

Use a map as a fast lookup table for coupon discounts.

You start with:

int subtotal = 100;
String coupon = "SAVE20";
HashMap<String, Integer> coupons = new HashMap<>();
coupons.put("SAVE10", 10);
coupons.put("SAVE20", 20);
coupons.put("SAVE50", 50);

Build:

Total: $80

Rules:

  • Look up coupon in coupons. If it is there, its value is the discount; if it is not (an unknown code), the discount is 0.
  • total = subtotal - discount.
  • Build the text "Total: $<total>" (e.g. "Total: $80"; an unknown coupon would give "Total: $100").
  • Store it in result, then print it with System.out.println(result).

Use coupons.getOrDefault(coupon, 0): it returns the value if the key is present, or 0 if it is missing.

In Java "Total: $" + total converts the number to text for you.

int subtotal = 100;
String coupon = "SAVE20";
HashMap<String, Integer> coupons = new HashMap<>();
coupons.put("SAVE10", 10);
coupons.put("SAVE20", 20);
coupons.put("SAVE50", 50);

int discount = coupons.getOrDefault(coupon, 0);
int total = subtotal - discount;
String result = "Total: $" + total;
System.out.println(result);

STEP 1 OF 4
    Ctrl + Enter to check

    JAVA · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V5 in Java, explained

    Problem overview

    This version applies a coupon to an order. The program starts with an int subtotal, a String coupon typed by the shopper and a HashMap<String, Integer> named coupons that maps each valid code to the amount it takes off: SAVE10 takes 10, SAVE20 takes 20 and SAVE50 takes 50.

    The program looks the coupon up. If the code is in the map, its value is the discount; otherwise the discount is 0. It then computes total = subtotal - discount and prints one line. With a subtotal of 100 and the coupon SAVE20:

    Total: $80

    With an unknown code such as FREE the same subtotal gives Total: $100, because an unknown code takes nothing off.

    Approach: a map as a lookup table

    One way to find the discount is a chain of if and else if tests, one per coupon. Every new coupon would then mean a new branch in the code. A map separates the data from the logic: the codes and their discounts sit in one table, and the program asks the table a single question, "what is this code worth?"

    A HashMap answers that question in constant time on average, however many coupons it holds. The code that uses it stays the same whether there are three coupons or three thousand.

    The one real decision is what to do with a code that is not in the map. The lesson's answer is a discount of 0, and Java has a method that expresses this directly.

    Step by step

    1. Look the coupon up. Create int discount with coupons.getOrDefault(coupon, 0). The first argument is the key to find, and the second is the value returned when the key is missing.
    2. Compute total. The subtotal minus the discount, which is what the customer pays.
    3. Build result. The text Total: $ joined with the number using +.
    4. Print result with System.out.println.

    The solution in Java

    int subtotal = 100;
    String coupon = "SAVE20";
    HashMap<String, Integer> coupons = new HashMap<>();
    coupons.put("SAVE10", 10);
    coupons.put("SAVE20", 20);
    coupons.put("SAVE50", 50);
    
    int discount = coupons.getOrDefault(coupon, 0);
    int total = subtotal - discount;
    String result = "Total: $" + total;
    System.out.println(result);
    

    The Java details worth a closer look:

    • get versus getOrDefault. coupons.get("FREE") returns null for a missing key. Assigning that to an int would fail at run time with a NullPointerException, because Java has to unbox the Integer into an int and null has no number inside. getOrDefault(coupon, 0) never returns null here, so the assignment is safe.
    • Boxed types. A HashMap holds objects, so the value type is Integer, not int. put("SAVE10", 10) boxes the number automatically, and the assignment to int discount unboxes it.
    • Keys are compared with equals. A HashMap finds a key by its hash code and then equals, so the lookup works for any string with the same characters, not only for the same object.
    • Imports. HashMap lives in java.util, so a standalone file needs import java.util.*;.
    • The map type on the left. The starter declares the variable as HashMap<String, Integer>. Declaring it as Map<String, Integer> works the same way for this lesson; the methods used here exist on both.

    Edge cases and common mistakes

    • Unknown code. FREE is not in the map, so the discount is 0 and the output is Total: $100.
    • Case matters. The keys are case-sensitive: save20 is not SAVE20, so a subtotal of 100 with save20 prints Total: $100. Calling coupon.toUpperCase() before the lookup would accept both spellings, but the lesson does not ask for it.
    • Using get alone. A missing key makes get return null, and the unboxing then throws a NullPointerException.
    • A discount larger than the subtotal. The lesson subtracts without checking. With a subtotal of 30 and SAVE50 the output is Total: $-20. Clamping the total at 0, for example with Math.max(0, subtotal - discount), would avoid a negative total, but this lesson uses the plain subtraction.
    • Subtracting from the wrong number. The discount comes off the subtotal, so the line is subtotal - discount, not the other way round.

    Testing

    With a subtotal of 100:

    • SAVE20 gives Total: $80.
    • SAVE10 gives Total: $90.
    • SAVE50 gives Total: $50.
    • FREE gives Total: $100.
    • save20 gives Total: $100.

    With a subtotal of 30, SAVE50 gives Total: $-20.

    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free