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/