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

为何additionalChoices方法未执行?汉堡类代码问题排查及优化建议

问题诊断与修复方案

首先,咱们来拆解你代码里导致additionalChoices方法没生效的核心问题,再一步步优化整个汉堡项目的实现。

一、为什么additionalChoices调用后总价没变化?

1. 字符串比较用错了==,而不是equals()

Java里==是比较对象的内存引用,不是字符串内容。比如你写的meatType == "chicken",只有当meatType和常量字符串是同一个内存对象时才会成立,实际业务中应该用"chicken".equals(meatType)(把常量放前面还能避免空指针异常)。这个问题在meatChoice、breadChoice、additionalChoices里都存在。

2. additionalChoices的逻辑完全走不通

  • 方法开头的while (addition1=="done"):你调用时传的是"tomato"、"olive",这个条件永远不成立,循环直接跳过,根本没执行里面的switch逻辑。
  • 就算进入循环,case "done"没有加break,会直接掉到default;而且循环条件是固定的,一旦进入就会无限循环。
  • 方法设计逻辑混乱:你想实现的是添加配料,但把循环写在了方法里,而实际调用是每次传一个配料,两者不匹配。

二、修复后的核心代码

先把上述问题修复,同时调整方法逻辑让它更合理:

class Burger {
    private String name;
    private String meatType;
    private String breadType;
    private double totalPrice = 0;

    // 常量定义,避免魔法值
    private static final double MEAT_BASE_PRICE = 3.0;
    private static final double BREAD_BASE_PRICE = 2.0;
    private static final double TOPPING_PRICE = 2.0;

    public Burger(String name, String meatType, String breadType) {
        System.out.println("Your name is " + name);
        this.name = name;
        this.meatType = meatType;
        meatChoice(meatType);
        this.breadType = breadType;
        breadChoice(breadType);
    }

    public double getTotalPrice() {
        System.out.println("You need to pay : " + totalPrice);
        return totalPrice;
    }

    public double meatChoice(String meatType) {
        // 用equals比较字符串,常量在前避免空指针
        if ("chicken".equals(meatType) || "beef".equals(meatType) || "ham".equals(meatType)) {
            System.out.println("You have selected " + meatType.substring(0,1).toUpperCase() + meatType.substring(1));
            totalPrice += MEAT_BASE_PRICE;
        } else {
            System.out.println("We do not have the meat selected, please try again");
        }
        return totalPrice;
    }

    public double breadChoice(String breadType) {
        if ("french".equals(breadType)) {
            System.out.println("You have selected french bread");
            totalPrice += BREAD_BASE_PRICE;
        } else if ("persian".equals(breadType)) {
            System.out.println("You have selected persian bread");
            totalPrice += BREAD_BASE_PRICE;
        } else {
            System.out.println("We do not have this bread type, please try again");
        }
        return totalPrice;
    }

    // 重构为添加单个配料的方法,循环逻辑移到外部(比如Main类)
    public double addTopping(String topping){
        switch (topping.toLowerCase()) { // 忽略大小写,提升用户体验
            case "tomato":
                System.out.println("You have selected Tomato for your topping.");
                totalPrice += TOPPING_PRICE;
                break;
            case "lettuce":
                System.out.println("You have selected Lettuce for your topping.");
                totalPrice += TOPPING_PRICE;
                break;
            case "onion":
                System.out.println("You have selected Onion for your topping.");
                totalPrice += TOPPING_PRICE;
                break;
            case "olive":
                System.out.println("You have selected Olive for your topping.");
                totalPrice += TOPPING_PRICE;
                break;
            default:
                System.out.println("Invalid topping: " + topping + ", please try again.");
        }
        return totalPrice;
    }
}

public class Main {
    public static void main(String[] args) {
        Burger basicBurger = new Burger("mehr","beef","french");
        basicBurger.addTopping("tomato");
        basicBurger.addTopping("olive");
        basicBurger.getTotalPrice();
        
        // 如果需要交互式添加配料,可以在这里加Scanner循环
        // Scanner scanner = new Scanner(System.in);
        // String input;
        // do {
        //     System.out.println("Enter a topping (type 'done' to finish):");
        //     input = scanner.nextLine();
        //     if (!"done".equals(input)) {
        //         basicBurger.addTopping(input);
        //     }
        // } while (!"done".equals(input));
        // basicBurger.getTotalPrice();
    }
}

三、进一步的优化建议

1. 用枚举替代字符串常量

把肉类、面包、配料这些固定选项定义成枚举,彻底避免拼写错误:

enum MeatType { CHICKEN, BEEF, HAM }
enum BreadType { FRENCH, PERSIAN }
enum Topping { TOMATO, LETTUCE, ONION, OLIVE }

之后Burger类的方法参数可以直接用这些枚举类型,不用再做字符串比较。

2. 引入建造者模式

如果后续汉堡的可选配置越来越多(比如不同尺寸、酱料),可以用建造者模式来构建对象,避免构造函数参数爆炸:

class BurgerBuilder {
    private String name;
    private MeatType meatType;
    private BreadType breadType;
    private List<Topping> toppings = new ArrayList<>();

    public BurgerBuilder setName(String name) {
        this.name = name;
        return this;
    }

    public BurgerBuilder setMeatType(MeatType meatType) {
        this.meatType = meatType;
        return this;
    }

    public BurgerBuilder addTopping(Topping topping) {
        this.toppings.add(topping);
        return this;
    }

    public Burger build() {
        return new Burger(this);
    }
}

3. 分离业务逻辑

把价格计算、输入验证这些逻辑从Burger类里抽出来,比如创建PriceCalculator、InputValidator类,让Burger类只专注于自身属性的管理,符合单一职责原则。

4. 异常处理增强

当用户输入无效选项时,不要只打印提示,可以抛出自定义异常(比如InvalidMeatTypeException),让调用者更灵活地处理错误场景。

内容的提问来源于stack exchange,提问作者Mehr s.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:38:32