Reputation: 139
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());
When I enter in true as a parameter to the constructor, my computeCost method still runs the block as if dependency were to == false. Is there any reason why?
Upvotes: 2
Views: 253
Reputation: 997
Your problem is not related to boolean. It is due to the division of integers. Please change the program as follows. 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());
}
}
Upvotes: 1
Reputation: 106400
You're falling victim to integer division. 20/100 == 0
, and anything multiplied by that is 0. To get around that, change your static final int
declarations to doubles.
static final double basicHealthFee = 250D;
static final double healthDiscount = 20D;
That D
defines a double literal.
Upvotes: 5
Reputation: 17724
You need to define basicHealthFee and healthDiscount as double
. Since you've defined them as integers you have the equation: healthFee = basicHealthFee - (basicHealthFee * (healthDiscount/100));
which becomes basicHealthFee - ( basicHealthFee * (20/100))
which becomes basicHealthFee - (basicHealthFee * 0)
-> basicHealthFee - 0
.
The if statement taking its value from your constructor is correct.
Upvotes: 4