You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何检查Java栈中用户输入的重复值以实现数量递增?

实现商品重复输入的数量统计功能

原代码使用Stack存储每个输入的商品,无法统计重复项的数量,我们可以通过以下方式修改来实现需求:

  1. 重构菜单数据结构:把菜单改成键值对形式,存储商品名称(统一小写)和对应价格,既方便验证输入是否有效,也能快速获取价格计算总价。
  2. 用Map统计数量:使用一个Map<String, Integer>来记录每个商品的下单数量,每次输入有效商品时,更新对应商品的数量(已存在则数量+1,不存在则初始化为1)。
  3. 输出统计结果:遍历统计Map,计算每个商品的总价并输出。

修改后的完整代码:

package stack;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Main {

    // 重构菜单:键为商品名(小写),值为价格
    private static final Map<String, Integer> MENU = new HashMap<>();
    static {
        MENU.put("cheeseburger", 6);
        MENU.put("pasta", 6);
        MENU.put("fries", 3);
        MENU.put("chicken", 20);
        MENU.put("soda", 2);
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // 用Map统计每个商品的下单数量
        Map<String, Integer> orderCounts = new HashMap<>();

        while (true) {
            String order = scanner.next();
            if (order.equalsIgnoreCase("OUT")) {
                break;
            }

            boolean isValidItem = isValidMenuItem(order);
            if (isValidItem) {
                // 统一转为小写,避免大小写差异导致统计错误
                String itemKey = order.toLowerCase();
                // 更新数量:存在则+1,不存在则设为1
                orderCounts.put(itemKey, orderCounts.getOrDefault(itemKey, 0) + 1);
            } else {
                System.out.println("Invalid item. Please choose from the menu.");
            }
        }

        // 输出统计结果
        for (Map.Entry<String, Integer> entry : orderCounts.entrySet()) {
            String itemName = entry.getKey();
            int quantity = entry.getValue();
            int price = MENU.get(itemName);
            int totalCost = quantity * price;
            // 把商品名首字母大写,输出更规范
            String formattedItem = itemName.substring(0, 1).toUpperCase() + itemName.substring(1);
            System.out.println(quantity + " " + formattedItem + " $" + totalCost);
        }

        System.out.println("END");
        scanner.close();
    }

    // 验证输入是否为有效商品
    private static boolean isValidMenuItem(String item) {
        return MENU.containsKey(item.toLowerCase());
    }
}

测试示例:
输入cheeseburger soda chicken cheeseburger OUT,输出结果为:

2 Cheeseburger $12
1 Soda $2
1 Chicken $20
END

内容的提问来源于stack exchange,提问作者Charlie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 05:12:07