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

Java结合if语句与HashSet限制仅可输入一次popcorn的排错

问题根因
  1. HashSet初始化位置错误:你将Set<String> set = new HashSet<>()写在了while循环内部,每一次循环都会生成一个全新的空Set,上一轮循环存入的popcorn记录会被完全清空,所以永远不会检测到重复值。
  2. 逻辑缺失&语法错误:原代码完全没有编写第二次输入popcorn时的报错分支,且exit的判断逻辑写在了while循环的大括号外侧,属于语法错误,无法正常编译运行。
修复后可运行代码
public void Popcorn() {
    boolean stop = false;
    // 将Set初始化移到循环外部,全程复用同一个Set存储记录
    Set<String> set = new HashSet<>();
    while (!stop) {
        String s = scanner.nextLine();
        if (s.equals("popcorn")) {
            if (!set.contains("popcorn")) {
                set.add("popcorn");
                int popcorn = 5;
                setPopCornValue(getPopCornValue() + popcorn);
                System.out.println("爆米花订购成功");
            } else {
                // 重复订购报错逻辑
                System.out.println("报错:仅允许订购一桶爆米花");
            }
            continue;
        }
        if (s.equals("exit")) {
            stop = true;
            break;
        }
        System.out.println("无效输入");
    }
}
核心修改说明
  • 把HashSet的实例化移到while循环之前,整个方法运行期间复用同一个Set存储已订购的商品,避免每轮循环清空记录
  • 拆分popcorn的判断逻辑,新增已存在时的报错分支
  • 把原代码错位的exit判断移回while循环内部,修正语法错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 18:36:02