【发布时间】:2013-03-26 00:03:29
【问题描述】:
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 一样。有什么原因吗?
【问题讨论】:
-
有一个未知数 - 从对象实例化到调用此方法之间会发生什么?就目前而言,如果
dependency,那么第一部分必须被执行。 -
你试过调试你的程序吗?
-
您是否正在使用为调用此方法而创建的同一个实例?是依赖
static吗?很多可能性。在您创建Health实例并调用方法computeCost()的位置发布代码。 -
@RyanSisson:还有更多。发布您的
main()方法。仅该代码并不能告诉我们适当的事件链。不要让锁定的问题吓到你;这将为您提供适当的时间以使问题处于可回答状态。 -
我不认为它每次都在运行虚假案例。你的问题是整数截断。 20/100 == 0 的整数数学运算,因此 basicHealthFee 总是乘以零。