Reputation: 13
I'm attempting to calculate how much tax a user should pay, based on wage. For example, calculating 20% in the first if
loop, this will be saved in generaltax
:
int generalTax = 0;
int userGrossPay = 50000;
if (userGrossPay <= 10600) {generalTax += 0;}
else if (((userGrossPay >= 10600) && (userGrossPay <= 31785))) { generalTax = ((20/100) * userGrossPay); }
else if (((userGrossPay >= 31786) && (userGrossPay <= 150000))) { generalTax = ((40/100) * userGrossPay); System.out.println(generalTax);}
else if (userGrossPay > 150001) {generalTax = ((45/100) * userGrossPay); }
else{System.out.println("error");};
userGrossPay -= generalTax;
System.out.println(userGrossPay);
However generalTax
pay is for some reason always stuck as 0
and is not properly updating on each iteration.
Upvotes: 1
Views: 55
Reputation: 17454
This is caused by integer division.
If you mix floating data type with integer, it will give you a data conversion by promotion.
For example:
int num = 5;
System.out.println(num / 2); //Gives you 2
System.out.println(num / 2.0); //Gives you 2.5
System.out.println(num * 2); //Gives you 10
System.out.println(num * 2.0); //Gives you 10.0
System.out.println(num + 2.5); //Gives you 7.5
If all operands in the operation are integers, your output will be integer as well. This is how you got into an integer division accidentally.
((20/100) * userGrossPay);
I see that you already accepted Eran's answer and understood what went wrong, I am here to give you some additional information.
Upvotes: 0
Reputation: 393851
Your problem is that you are always adding 0
or assigning 0
to generalTax
.
For example, (20/100) * userGrossPay
is 0
, since 20/100
is 0
due to int
division. Change it too 0.2 * userGrossPay
or 20.0/100 * userGrossPay
. Similarly change all other places where you divide two integers.
Upvotes: 6