Buy List & Count Total Price


Submit solution

Points: 60 (partial)
Time limit: 1.0s
Memory limit: 256M

Authors:
Problem type
Allowed languages
Java 19, Java 8

題目說明

請設計一程式,根據使用者輸入的商品,記錄到購物清單
輸入結束後,根據購物清單紀錄的商品數量,從HashMap找出對應的商品價格計算總金額
最後輸出購物清單&總金額

    HashMap<String, Integer> fruitPrice = new HashMap<>();
    // Add some key-value pairs to the fruitPrice
    fruitPrice.put("apple", 10);
    fruitPrice.put("banana", 20);
    fruitPrice.put("cherry", 30);

輸入

一連串商品名稱(以空格分開),輸入.時結束

輸出

若找不到某商品,印出Item not found: (某商品)

最後,印出購物清單,以及所有商品金額的加總
// 購物清單的格式請用:System.out.println("Buy List: " + buyList);
// 總金額的格式請使用:System.out.printf("Total Price: $%,d", totalPrice);

測試資料0 輸入

apple banana banana apple cherry .

測試資料0 輸出

Buy List: {banana=2, apple=2, cherry=1}
Total Price: $90

測試資料1 輸入

apple berry banana banana apple juice cherry apple .

測試資料1 輸出

Item not found: berry
Item not found: juice
Buy List: {banana=2, apple=3, cherry=1}
Total Price: $100

Comments


  • 0
    scu09156146  commented on May 31, 2024, 2:40 p.m.

    題解

    import java.util.HashMap;
    import java.util.Scanner;
    
    public class BuyList_CountTotal {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            HashMap<String, Integer> fruitPrice = new HashMap<>();
            // Add some key-value pairs to the fruitPrice
            fruitPrice.put("apple", 10);
            fruitPrice.put("banana", 20);
            fruitPrice.put("cherry", 30);
    
            Scanner in = new Scanner(System.in);
            HashMap<String, Integer> buyList = new HashMap<>();
            String item = in.next();
            while (!item.equals(".")) {
                if (buyList.containsKey(item)) { // 檢查清單是否已包含這項物品
                    buyList.put(item, buyList.get(item) + 1); // 更新某key的value
                } else {
                    if (fruitPrice.containsKey(item))
                        buyList.put(item, 1); // 加入新的key-value資料
                    else
                        System.out.println("Item not found: " + item); // 無此商品,輸出訊息
                }
                item = in.next();
            }
            in.close(); 
    
            // 印出購物清單
            System.out.println("Buy List: " + buyList);
            // 計算總金額
            int totalPrice = 0;
            for (String item_buy : buyList.keySet()) {
                totalPrice += fruitPrice.get(item_buy) * buyList.get(item_buy);
            }
            System.out.printf("Total Price: $%,d", totalPrice);
        }
    
    }