布尔if语句

时间:2013-04-04 04:05:10

标签: java bluej

public class Health
{
    boolean dependency;
    String insuranceOwner = "";
    static final int basicHealthFee = 250;
    static final int healthDiscount = 20;

    public Health(boolean dependent, String insurance)  
    {  
        dependency = dependent;  
        insuranceOwner = insurance;  
    }

    public double computeCost()
    {
        double healthFee;
        if (dependency == true)
        {
            healthFee = basicHealthFee - (basicHealthFee * (healthDiscount/100.0));
        }
        else 
        {
            healthFee = basicHealthFee;
        }

        return healthFee;
    }
}

 Health h34 = new Health(true, "Jim");         
 System.out.println("discount price: " + h34.computeCost());

当我输入true作为构造函数的参数时,我的computeCost方法仍然运行块,就好像依赖项是== false。有什么理由吗?

3 个答案:

答案 0 :(得分:5)

你是整数分裂的受害者。 20/100 == 0,任何乘以的数字为0.要解决此问题,请将static final int声明更改为双打。

static final double basicHealthFee = 250D;
static final double healthDiscount = 20D;

D定义了double literal

答案 1 :(得分:4)

您需要将basicHealthFee和healthDiscount定义为double。由于您已将它们定义为整数,因此您可以使用等式:healthFee = basicHealthFee - (basicHealthFee * (healthDiscount/100));,它变为basicHealthFee - ( basicHealthFee * (20/100)),变为basicHealthFee - (basicHealthFee * 0) - > basicHealthFee - 0

if语句从构造函数中获取其值是正确的。

答案 2 :(得分:1)

您的问题与布尔值无关。这是由于整数的划分。请按如下方式更改程序。 static final double healthDiscount = 20d; static final double basicHealthFee = 250d;

package com.stackoverflow.test;

public class Health {
    boolean dependency;
    String insuranceOwner = "";
    static final double basicHealthFee = 250d;
    static final double healthDiscount = 20d;

    public Health(boolean dependent, String insurance) {
        dependency = dependent;
        insuranceOwner = insurance;
    }

    public double computeCost() {
        double healthFee;
        if (dependency == true) {
            healthFee = basicHealthFee
                    - (basicHealthFee * (healthDiscount / 100.0d));
        } else {
            healthFee = basicHealthFee;
        }

        return healthFee;
    }

    public static void main(String args[]) {
        Health h34 = new Health(true, "Jim");
        System.out.println("discount price: " + h34.computeCost());
    }
}