java - boolean if 语句

标签 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 方法仍然运行该 block ,就好像依赖项 == false 一样。有什么原因吗?

最佳答案

您正在成为整数除法的牺牲品。 20/100 == 0,任何乘以它的结果都是 0。要解决这个问题,请将您的 static final int 声明更改为 double。

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

D 定义了一个 double literal .

关于java - boolean if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15802314/

相关文章:

java - 马文 3 : Is it possible to build a JDBC-3 driver with Java 6?

java - 我应该如何克隆嵌套 ArrayList?

java - 我的 return 语句不使用用户插入的数据

java - 仅创建从 BLUEJ 到 EXE 文件的返回方法

java - JAXB 代码生成 : restricted type -> how to remove a zero occurrence field?

java - 如何使用 jMockit 和 TestNG 在最终类中验证对静态方法的调用?

java - 如何让 ANT 将 Java 程序的输出发送到特定文件?

java - 复制到带有字符串的类时出现空指针异常

java - 在 BlueJ 中打印对象数组

java - 向文本文件添加空白空间的最佳方法?