如果语句混淆方法

时间:2016-05-30 23:11:39

标签: java

我在理解此代码时遇到问题

public void changeHealthCoefficient(double delta)

将delta参数中传递的值添加到healthCoefficient实例变量中。

参数delta可以是正数或负数,但如果healthCoefficient的新值小于或等于MINIMUM_HEALTH_COEFFICIENT,则除了更改{{1}的值之外},将healthCoefficient实例变量设置为isAlive

如果false的新值大于healthCoefficient,请将MAXIMUM_HEALTH_COEFFICIENT设置为healthCoefficient

我做了

MAXIMUM_ HEALTH_COEFFICIENT

而不是

if (newHealthCoefficient  <= MINIMUN_HEALTH_COEFFICIENT)
    newHealthCoefficient = MINIMUN_HEALTH_COEFFICIENT

2 个答案:

答案 0 :(得分:0)

根据您所描述的内容,您似乎想要这样的内容:

public void changeHealthCoefficient(double delta)
{
    // adds the value passed in the delta parameter to the 
    // healthCoefficient instance variable
    healthCoefficient += delta;

    // if the new value of healthCoefficient would be less than or equal 
    // to MINIMUM_HEALTH_COEFFICIENT , in addition to changing the value of 
    // healthCoefficient, set the isAlive instance variable to false.
    if (healthCoefficient  <= MINIMUN_HEALTH_COEFFICIENT)
    {
        isAlive = false;
    }

    // if the new value of healthCoefficient would be greater than 
    // MAXIMUM_HEALTH_COEFFICIENT, set healthCoefficient to 
    // MAXIMUM_HEALTH_COEFFICIENT.
    if (healthCoefficient > MAXIMUM_HEALTH_COEFFICIENT)
    {
        healthCoefficient = MAXIMUM_HEALTH_COEFFICIENT;
    }
}

答案 1 :(得分:0)

实施最小值或最大值的简单方法是使用Math.minMath.max方法。

例如:

healthCoefficient = Math.Min(healthCoefficient, MAXIMUM_HEALTH_COEFFICIENT);

将值设置为当前值和常量中较小的值。

我建议,根据您的问题,您的健康系数值应该属于自己的类别。非常长的变量名称可能表示您试图将变量与不相关类中的不相关变量区分开来。

因此,您的代码可能更清晰,例如:

class HealthCoefficient {
    private static final double MAX = 100.0;
    private static final double MIN = 30.0;
    private double value;

    public void change(double delta) {
        value += delta;
        value = Math.min(value, MAX);
        value = Math.max(value, MIN);
    }

    public boolean isAlive() {
        return value > MIN;
    }
}