Project: Shopping Cart

Lab Java Advanced 30 points

Build a shopping cart. First read p products (name price, price in whole rupees). Then read c cart lines (name quantity). Ignore products that don't exist (print Unknown item: <name>). Adding the same product again increases its quantity.

Then print each cart item in the order it was first added as <name> x<qty> = <line total>, then Subtotal: <sum>. If the subtotal is 1000 or more, a 10% discount applies: print Discount: <amount> (integer division). Finally print Total: <amount>.

Input

p, then p product lines, then c, then c cart lines.

Output

As described above.

Example

Input

3
pen 20
book 450
bag 700
4
book 1
pen 3
laptop 1
book 1

Output

Unknown item: laptop
book x2 = 900
pen x3 = 60
Subtotal: 960
Total: 960
Sample input available Sample output available
Editor
Java

Hints

A LinkedHashMap keeps the cart in the order items were first added.

cart.getOrDefault(name, 0) + qty adds to an existing quantity.

Only print the Discount line when there is one.

Solution explanation

One map holds the price list, another holds the cart. Keeping them separate keeps the code simple.

Show solution
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int p = sc.nextInt();
        HashMap<String, Integer> prices = new HashMap<>();
        for (int i = 0; i < p; i++) {
            prices.put(sc.next(), sc.nextInt());
        }
        int c = sc.nextInt();
        LinkedHashMap<String, Integer> cart = new LinkedHashMap<>();
        for (int i = 0; i < c; i++) {
            String name = sc.next();
            int qty = sc.nextInt();
            if (!prices.containsKey(name)) {
                System.out.println("Unknown item: " + name);
            } else {
                cart.put(name, cart.getOrDefault(name, 0) + qty);
            }
        }
        int subtotal = 0;
        for (Map.Entry<String, Integer> e : cart.entrySet()) {
            int line = prices.get(e.getKey()) * e.getValue();
            System.out.println(e.getKey() + " x" + e.getValue() + " = " + line);
            subtotal += line;
        }
        System.out.println("Subtotal: " + subtotal);
        int discount = subtotal >= 1000 ? subtotal / 10 : 0;
        if (discount > 0) {
            System.out.println("Discount: " + discount);
        }
        System.out.println("Total: " + (subtotal - discount));
    }
}
Output
Answer
HOME LABS COMMUNITY DASHBOARD