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

Java问题:getRoadtaxPrice()未正确获取车辆类型及动力系统值

问题排查与修复方案

问题1:动力系统参数未正常更新

原因

Vehicle类中setPowertrain setter方法赋值顺序写反,没有将用户输入的值赋值给类的成员变量,反而用成员变量的初始值覆盖了输入的参数。

修复代码

将setPowertrain方法修改为:

//Setter
public void setPowertrain(String powertrain){
    this.powertrainVehicle = powertrain;
}

同理setTransmission方法也存在相同的赋值顺序错误,建议同步修改:

//Setter
public void setTransmission(String transmission){
    this.transmissionVehicle = transmission;
}

问题2:道路税价格始终返回0

原因

getRoadtaxPrice方法中所有字符串比较都使用了==运算符,Java中==用于比较字符串的内存地址而非实际内容,用户输入的字符串和代码中硬编码的字符串常量地址不同,导致所有判断分支都不触发,最终返回默认值0。

修复代码

将所有字符串比较改为equals()方法:

public double getRoadtaxPrice(){
    double price = 0;
    
    if (typeVehicle.equals("Car")){
        if (powertrainVehicle.equals("Gasoline")){
            price = 200;
        }
        else if (powertrainVehicle.equals("Hybrid")){
            price = 100;
        }
        else if (powertrainVehicle.equals("Electric")){
            price = 50;
        }
        else{
            price = 0;
        } 
    }
    else if (typeVehicle.equals("SUV") || typeVehicle.equals("MPV")){
        if (powertrainVehicle.equals("Gasoline")){
            price = 300;
        }
        else if (powertrainVehicle.equals("Hybrid")){
            price = 150;
        }
        else if (powertrainVehicle.equals("Electric")){
            price = 100;
        }
        else{
            price = 0;
        }                
    }
    else if (typeVehicle.equals("Lorry")){
        powertrainVehicle = "All";
        price = 400;
    }
    return price;
}

额外注意事项

主类中使用Scanner的nextInt()方法读取数值后,不会自动消费输入末尾的换行符,如果后续调用nextLine()会直接读取到空字符串,建议每次调用nextInt()后补充一行sc.nextLine()吃掉残留的换行符,避免后续输入异常。

内容的提问来源于stack exchange,提问作者Azumi-san

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:36:07