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

Java枚举使用float计算咖啡价格时出现空指针异常求助

问题根源

你遇到的NullPointerException本质是Ingredients枚举常量未正确初始化,导致集合中存在null元素。具体原因:

  • 你将Ingredients的cost字段改为float,但枚举构造函数仍为Ingredients(int cost),而定义枚举常量时传入的0.25、1.25是默认的double类型浮点数,Java无法自动将double转为int,导致枚举实例初始化失败,最终这些常量实际为null。
  • 当你把这些无效的枚举常量添加到集合后,遍历调用ingredient.getCost()时自然触发空指针异常。

此外还有两个影响结果正确性的问题:

  1. calculateCost方法中totalCost用int类型存储,会导致浮点数相加时被截断,无法得到预期的6.5。
  2. 枚举常量的浮点数参数未加f后缀,默认以double类型传入,赋值给float字段时可能存在精度损失。
修复步骤

1. 修正Ingredients枚举的构造函数

将构造函数参数类型改为float,匹配字段类型,同时给浮点数参数加上f后缀:

public enum Ingredients { 
    SUGAR(0.25f), 
    MILK(1.25f), 
    CREAM(1.75f);
    
    private final float cost;

    // 构造函数参数改为float
    Ingredients(float cost) {
        this.cost = cost;
    }

    public float getCost() {
        return cost;
    }
}

2. 修改calculateCost方法的总价存储类型

把totalCost从int改为float,避免浮点数相加被截断:

public static float calculateCost(Sizes size, List<Ingredients> ingredients) {
    // 用float存储总价,先将size的int成本转为float
    float totalCost = size.getCost();
    for (Ingredients ingredient : ingredients) {
        totalCost += ingredient.getCost();
    }
    return totalCost;
}

3. 可选:修正拼写错误

输出语句中的suger是拼写错误,建议改为sugar:

System.out.println("Cost of a small size coffee with milk and sugar: " + calculateCost(Sizes.SMALL, ingredients));
修复后运行结果

完成上述修改后,代码运行会输出:

Cost of a small size coffee with milk and sugar: 6.5

内容的提问来源于stack exchange,提问作者Örlygur Hugason

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 04:41:10