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
couponincoupons. If it is there, its value is thediscount; if it is not (an unknown code), the discount is0. 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 withSystem.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);
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
