2
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 一样。有什么理由吗?

4

3 回答 3

5

您正在成为整数除法的受害者。 20/100 == 0,乘以 0。要解决这个问题,请将您的static final int声明更改为双精度数。

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

D定义了一个双重文字

于 2013-04-04T04:26:09.240 回答
4

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

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

于 2013-04-04T04:28:01.830 回答
1

您的问题与布尔值无关。这是由于整数的除法。请按以下方式更改程序。静态最终双健康折扣 = 20d;静态最终双基本健康费 = 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());
    }
}
于 2013-04-04T04:37:07.163 回答