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
- Look the coupon up. Create
int discountwithcoupons.getOrDefault(coupon, 0). The first argument is the key to find, and the second is the value returned when the key is missing. - Compute
total. The subtotal minus the discount, which is what the customer pays. - Build
result. The textTotal: $joined with the number using+. - Print
resultwithSystem.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:
getversusgetOrDefault.coupons.get("FREE")returnsnullfor a missing key. Assigning that to anintwould fail at run time with aNullPointerException, because Java has to unbox theIntegerinto anintandnullhas no number inside.getOrDefault(coupon, 0)never returnsnullhere, so the assignment is safe.- Boxed types. A
HashMapholds objects, so the value type isInteger, notint.put("SAVE10", 10)boxes the number automatically, and the assignment toint discountunboxes it. - Keys are compared with
equals. AHashMapfinds a key by its hash code and thenequals, so the lookup works for any string with the same characters, not only for the same object. - Imports.
HashMaplives injava.util, so a standalone file needsimport java.util.*;. - The map type on the left. The starter declares the variable as
HashMap<String, Integer>. Declaring it asMap<String, Integer>works the same way for this lesson; the methods used here exist on both.
Edge cases and common mistakes
- Unknown code.
FREEis not in the map, so the discount is 0 and the output isTotal: $100. - Case matters. The keys are case-sensitive:
save20is notSAVE20, so a subtotal of 100 withsave20printsTotal: $100. Callingcoupon.toUpperCase()before the lookup would accept both spellings, but the lesson does not ask for it. - Using
getalone. A missing key makesgetreturnnull, and the unboxing then throws aNullPointerException. - A discount larger than the subtotal. The lesson subtracts without checking. With a subtotal of 30 and
SAVE50the output isTotal: $-20. Clamping the total at 0, for example withMath.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:
SAVE20givesTotal: $80.SAVE10givesTotal: $90.SAVE50givesTotal: $50.FREEgivesTotal: $100.save20givesTotal: $100.
With a subtotal of 30, SAVE50 gives Total: $-20.
