콘텐츠로 이동

Mini Project Set 6 Answer: Cafe Order Manager

Complete Program

import java.util.ArrayList;
import java.util.HashMap;

class CafeOrder {
    private String customerName;
    private HashMap<String, Double> menu;
    private ArrayList<String> itemNames;
    private double discountPercent;

    public CafeOrder(String customerName) {
        this.customerName = customerName;
        this.menu = new HashMap<>();
        this.itemNames = new ArrayList<>();
        this.discountPercent = 0.0;
    }

    public void addMenuItem(String itemName, double price) {
        menu.put(itemName, price);
    }

    public void addItem(String itemName) {
        if (menu.containsKey(itemName)) {
            itemNames.add(itemName);
        }
    }

    public void applyDiscount(double percent) {
        if (percent > 0 && percent < 100) {
            discountPercent = percent;
        }
    }

    public int itemCount() {
        return itemNames.size();
    }

    public double totalSpent() {
        double total = 0.0;

        for (String name : itemNames) {
            total += menu.get(name);
        }

        return total * (100.0 - discountPercent) / 100.0;
    }

    public double averageItemPrice() {
        if (itemCount() == 0) {
            return 0.0;
        }
        return totalSpent() / itemCount();
    }

    public boolean qualifiesForLoyalty() {
        return itemCount() >= 4 && totalSpent() >= 20.0;
    }

    public String getSummary() {
        return customerName + ": " + itemCount() + " items, $"
                + String.format("%.2f", totalSpent()) + " total";
    }
}

public class Main {
    public static void main(String[] args) {
        CafeOrder order = new CafeOrder("Mina");

        order.addMenuItem("Americano", 5.50);
        order.addMenuItem("Sandwich", 8.00);
        order.addMenuItem("Cake", 12.00);
        order.addMenuItem("Water", 1.00);

        order.addItem("Americano");
        order.addItem("Sandwich");
        order.addItem("Unknown Item");
        order.addItem("Cake");
        order.addItem("Water");
        order.applyDiscount(10.0);

        System.out.printf("%.2f%n", order.averageItemPrice());
        System.out.println(order.qualifiesForLoyalty());
        System.out.println(order.getSummary());
    }
}

Output

5.96
true
Mina: 4 items, $23.85 total

Key Points

  • The constructor initializes both collections, so every method can use them immediately.
  • containsKey prevents an unknown item from being added to the order.
  • totalSpent() looks up each price from the menu map and then applies the discount.
  • averageItemPrice() checks the item count before dividing, so it never divides by zero.
  • qualifiesForLoyalty() needs &&: reaching only one of the two requirements is not enough.
  • String.format("%.2f", totalSpent()) fixes the total to two decimal places.