Buy List


Submit solution

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

Authors:
Problem types
Allowed languages
Java 19, Java 8

題目說明

請設計一類似購物清單的程式,讓使用者可以輸入要買的商品,存到HashMap,最後輸出整個HashMap

import java.util.*;
public class ContactInfo {

    public static void main(String[] args) {
        HashMap<String, Integer> buyList = new HashMap<>();

        /*
            補上缺少的程式碼
        */

        // 印出購物清單
        System.out.println(buyList);

    }

}

輸入

先輸入要買的商品,當輸入為.結束
注意,輸入的商品可能有重複

輸出

購物清單

測試資料 輸入

apple banana orange cheese yogurt banana orange .

測試資料 輸出

{banana=2, orange=2, apple=1, yogurt=1, cheese=1}

// HashMap無序,無需考慮輸出的排序問題


Comments


  • 0
    scu09156146  commented on May 21, 2024, 2:17 p.m. edited

    題解

    應用題 // 參考試算表A268試算表A270筆記

    import java.util.HashMap;
    import java.util.Scanner;
    
    public class BuyList {
    
        public static void main(String[] args) {
            HashMap<String, Integer> buyList = new HashMap<>();
    
            Scanner in = new Scanner(System.in);
            String item = in.next();
            while (!item.equals(".")) {
                if (buyList.containsKey(item)) // 檢查清單是否已包含這項物品
                    buyList.replace(item, buyList.get(item) + 1); // 更新某key的value
                else
                    buyList.put(item, 1); // 加入新的key-value資料
                item = in.next();
            }
            in.close();
    
            // 印出購物清單
            System.out.println(buyList);
        }
    
    }