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.printf("Total Price: $%,d", totalPrice);

測試資料0 輸入

apple banana banana apple cherry .

測試資料0 輸出

Total Price: $90

測試資料1 輸入

apple berry banana banana apple juice cherry apple .

測試資料1 輸出

Item not found: berry
Item not found: juice
Total Price: $100

Comments


  • 0
    scu09156146  commented on May 23, 2024, 12:11 p.m.

    題解

    參考課堂範例A269A270

    import java.util.HashMap;
    import java.util.Scanner;
    
    public class TotalPrice {
    
        public static void main(String[] args) {
            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 input = new Scanner(System.in);
            int totalPrice = 0; // 加總的金額
            String item = input.next();
            while (!item.equals(".")) {
                // 檢查是否包含"某商品"
                if (fruitPrice.containsKey(item))
                    totalPrice += fruitPrice.get(item);             // 從HashMap取得商品價格
                else
                    System.out.println("Item not found: " + item);  // 無此商品,輸出訊息
                // 接下一個輸入的商品
                item = input.next();
            }
            input.close();
    
            // 印出總金額,要三位一撇
            System.out.printf("Total Price: $%,d", totalPrice);
        }
    
    }