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

Java使用switch语句返回null而非预期结果,代码错误排查求助

代码错误排查及修正

存在的问题

  • 分类计算逻辑完全错误
    • Java中switch不支持double类型参数,且你的case 1、case 2是精确值匹配,和价格区间逻辑完全无关,永远无法命中你写的价格判断分支
    • 价格判断条件中使用了未定义的size变量,应为price < 7000
    • 分类计算方法从未被主动调用,类的Category属性默认初始值为null,直接调用getCategory()自然返回null
  • setter方法调用语法错误:setPrice是方法不是属性,不能用PhoneN.setPrice=6500赋值,需改为方法调用格式
  • 对象名引用错误:实例化的对象名为PhoneN,打印时错误引用了不存在的PhoneA对象
  • 命名不规范(可选优化):属性名首字母建议小写,业务方法不要和属性重名,避免混淆

修正后代码

Phone类

public class Phone {
    // 修正属性命名规范
    private String brand;
    private double price;
    private String category;

    public void setPrice(double newPrice) {
        this.price = newPrice;
        // 价格变动时自动计算分类,无需手动调用
        calculateCategory();
    }

    public double getPrice() {
        return price;
    }

    public void setBrand(String newBrand) {
        this.brand = newBrand;
    }

    public String getBrand() {
        return brand;
    }

    public String getCategory() {
        return category;
    }

    // 替换错误的switch逻辑,直接用if分支实现区间判断
    private void calculateCategory() {
        if (price >= 8000) {
            category = "Expensive";
        } else if (price >= 5000 && price < 7000) {
            category = "Normal";
        } else {
            category = "Cheap";
        }
    }
}

TestPhone类

public class TestPhone {
    public static void main(String[] args) {
        Phone phoneN = new Phone();
        // 修正setter调用语法
        phoneN.setPrice(6500);
        // 修正对象名引用错误
        System.out.println(phoneN.getCategory());
    }
}

运行结果

执行后输出Normal,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:54:04