Working out taxable income Java - java

I have just finished a Java test at university and I know that I have answered a particular question wrong and would just like some help / clarification please?
The question was as follows:
implement a method that takes someones income and works out the tax.
If that person earns less than 7500 then tax = 0.
If that person earns between 7501 and 45000 then tax = 20%, less the 7500, which is tax free.
Finally, if that person earns above 45001 then tax = 40%, less the income in the 20% bracket, and then less the 7500 which is tax free.
As time was running short, I just did a basic if else statement showing income and tax brackets, example below.
public static double incomeTax(double income){
if(income <= 7500){
income = income * 0;
}
else if(income >= 7501 && income <= 45000){
income = income * 0.8;
}
else(income >= 45001){
income = income * 0.6;
}
return income;
}
I know that the code is not correct, no where near, but as it was coming to the end of the test I gave it a go in a hope just to get a mark for the if else statements.
I would really appreciate any help here.
Thank you.
After great feedback, this is what I came back with (with a LOT of help!!:] )...
import java.util.Scanner;
public class TaxableIncome
{
public static void main(String[] args){
netIncome();
}
public static double netIncome() {
double income = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter income: ");
income = in.nextDouble();
System.out.println();
double tax1 = 0;
double tax2 = 0;
double totalTax = tax1 + tax2;
// high income bracket
if (income > 45000) {
double part1 = income - 45000; // part = income - 45000
tax1 += part1 * 0.4; // tax = tax + part * 0.4
System.out.println("High Tax Band - Greater than 45000: " + tax1);
}
// medium income bracket
if (income > 7500) {
double part2 = income - 7500;
tax2 += part2 * 0.2;
System.out.println("Medium Tax Band - Greater than 7500: " + tax2);
}
System.out.println("Total Tax = " + (tax1 + tax2));
// tax for low income is zero, we don't need to compute anything.
return totalTax;
}
}

A simple answer would be as this:
public static double netIncome(double income) {
double tax = 0;
// high income bracket
if (income > 45000) {
double part = income - 45000;
tax += part * 0.4;
income = 45000;
}
// medium income bracket
if (income > 7500) {
double part = income - 7500;
tax += part * 0.2;
}
// tax for low income is zero, we don't need to compute anything.
return tax;
}
This way you calculate the tax for each tax bracket and sum them.

I see nothing wrong with the logic. The main issue you had was you just need to return the income tax, not the total income. So the value you needed to return was income*whateverPercentTax.
Also, I would've tried:
if(income < 7001){
}else if(income >=45001){
}else{}
But that is just me.

I would start with something like this:
public static double incomeTax(int income) {
final double band00Income = (double) Math.min(income, 7500);
final double band20Income = (double) Math.min(income - band00Income, 45000 - 7500);
final double band40Income = (double) Math.max(income - 45000, 0);
final double tax = band20Income * 0.2 + band40Income * 0.4;
return tax;
}
Note that income is an int due to a peculiarity of the tax calculation in the UK - it also solves the problem with the unspecified cases between 7500.01 and 7500.99 inclusive.
A better solution would extract constants for all the magic numbers. An even better solution would generalise the bands and rates into a table so that they can be changed easily.
A complete answer might include test cases like this:
import org.junit.Assert;
import org.junit.Test;
public class TestTax
{
public static final double DELTA = 0.1;
#Test
public void testTax() {
Assert.assertEquals(0.0, incomeTax(-3000), DELTA);
Assert.assertEquals(0.0, incomeTax(0), DELTA);
Assert.assertEquals(0.2, incomeTax(7501), DELTA);
Assert.assertEquals(3000.0, incomeTax(22500), DELTA);
Assert.assertEquals(7500.0, incomeTax(45000), DELTA);
Assert.assertEquals(7500.4, incomeTax(45001), DELTA);
Assert.assertEquals(25500.0, incomeTax(90000), DELTA);
}
public static double incomeTax(int income) {
final double band00Income = (double) Math.min(income, 7500);
final double band20Income = (double) Math.min(income - band00Income, 45000 - 7500);
final double band40Income = (double) Math.max(income - 45000, 0);
final double tax = band20Income * 0.2 + band40Income * 0.4;
return tax;
}
}

You'd have to tax things in bands. Dirty (untested) code:
public static double incomeTax(double income){
double tax = 0;
if(income > 7500){
tax += Math.min(45000-7500, income-7500)*.2;
}
if(income > 45000){
tax += (income-45000)*.4;
}
return tax;
}

You need to attempt to apply the tax rates more than once. Your code only hits one tax bracket. If I made 100k, I would have been taxed at 40% for the whole 100k. Here is something I came up with quickly.
public static double incomeTax(double income)
{
double tax = 0.0;
int midLevel = 7500;
int highLevel = 45000;
if (income <= 7500)
{
// Could early exit at this point and return already set tax
tax = 0.0;
}
if (income > midLevel)
{
// Find range of income > 7500, less than 4500. 37499 max
double taxableIncome = Math.min(income - midLevel, highLevel - midLevel - 1);
tax += taxableIncome * 0.2;
}
if (income > highLevel)
{
// Income above 45k
double taxableIncome = income - highLevel;
tax += taxableIncome * 0.4;
}
return tax;
}

You could try this, just copy your income brackets in the bracket array. Make sure you have infinity in bracket array and start with 0 in rate array.
import java.util.Scanner;
import java.text.DecimalFormat;
class IncomeTaxWithBrackets {
public static void main(String[] args) {
double infinity = Double.POSITIVE_INFINITY;
double [] bracket = {0, 7565, 25903, 54987, 121121, 567894, infinity};
double [] rate = {0, 0.10, 0.15, 0.20, 0.25, 0.30, 0.35};
// bracket[0] to bracket[1] are assigned rate[1]
double income = 0;
double tax = 0;
System.out.print("\nPlease enter your income: ");
Scanner keyboard = new Scanner (System.in);
DecimalFormat dollar = new DecimalFormat ("$#,##0.00");
income = keyboard.nextDouble();
int x,i;
for (i=0; i <= 5; i++) {
if (income > bracket[i] && income <= bracket[i+1]) {
for (x=0; x<i; ++x) {
tax = tax + (bracket[x+1] - bracket[x]) * rate[x+1];
}
tax = tax + (income - bracket[i]) * rate[i+1];
}
}
System.out.println("\nWith a taxable income of "+dollar.format(income)+", your personal income tax is "+dollar.format(tax));
}
}
Let me know what you think.

Related

Interest Calculator

Problem with my code for calculator - output values not correct
Here is my code, any response would be appreciated.
import java.util.Scanner;
public class Savings {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
//ask for initial amount
System.out.print("What is the initial savings amount? ");
double initialAmount = console.nextDouble();
// ask for number of months
System.out.print("What is the number of months to save? ");
int months = console.nextInt();
//ask for interest rate
System.out.print("What is the annual interest rate? ");
double interestRate = console.nextDouble();
//calculate total
double monthlyInterest = ((interestRate/100)*(1/12));
double number1 = (monthlyInterest + 1);
double number2 = Math.pow(number1, months);
double total = (initialAmount*number2);
System.out.println("$" + initialAmount + ", saved for " + months + " months at " + interestRate + "% will be valued at $" + total);
console.close();
}
}
final value ends up being the same value as initial
Change this:
double monthlyInterest = ((interestRate/100)*(1/12));
to
double monthlyInterest = (interestRate / 100) * (1.0 / 12.0);
You're trying to do integer division in floating-point context, so in monthlyInterest you are essentially multiplying interestRate / 100 with 0.
Add d with the numbers to convert them into double and keep the decimal value, this way -
double monthlyInterest = ((interestRate/100d)*(1/12d));
If you do 1/12 with integers, the output will be 0, but with 1/12d it will be 0.08333333333333333
Also, you can get rid of the extra parenthesis -
double monthlyInterest = (interestRate/100d)*(1/12d);
...
double number1 = monthlyInterest + 1;
...
double total = initialAmount * number2;

When finding yearly compound interest why does Java compute interestRate/100 rather than just interestRate?

Here's the textbook problem:
A certain bank offers 6.5% interest on savings accounts, compounded
annually. Create a table that shows how much money a person will
accumulate over a period of 25 years, assuming that the person makes
an initial investment of $1000 and deposits $100 each year after the
first. Your table should indicate for each year the current balance,
the interest, the new deposit, and the new balance.
This is my code. It is correct:
public void compoundAnnual() {
double investment = 1000;
int year = 25;
double newDeposit = 0;
double newBalance;
double interestRate = 6.5;
double interest;
double deposit = 0;
System.out.println("Year Interest New Deposit New Balance");
System.out.println("------------------------------------------------------");
for (int i = 1; i <= year; i++) {
if (i == 1)
{
newDeposit = investment;
}
newBalance = newDeposit * Math.pow((1 + (interestRate/100)), 1);
interest = newBalance - newDeposit;
System.out.printf("%1d %10.2f %20.2f %22.2f \n ", i, interest, newDeposit, newBalance);
newDeposit = newBalance + 100;
}
}
However, when finding the newBalance I am confused why
Math.pow((1 + (interestRate/100)), 1);
is correct.
Why wouldn't
Math.pow((1 + (interestRate), 1);
be correct if interestRate was set to 0.65? When I set interestRate equal to 0.65 the output for this is wrong and I don't understand why. Wouldn't they be the same thing?
Why wouldn't ... be correct if interestRate was set to 0.65?
Because 0.65 corresponds to 65% interest.
Try 0.065 (= 6.5 / 100).
(Note that this is nothing specific to programming, it's just arithmetic).
interestRate should be 0.065 in your case not 6.5, because 6.5/100=.065.If you hard code interestRate as 6.5 you won't get expected output.
Try giving
interestRate =.065
it will work fine.

Method value's won't go to other scopes?

I'm very very new, I'll try my best to word best I can (english is not my first language.) I hope my topic name is not confusing, right to the point.
public static double dogTotalFee(double totalFee)//calculate total fee (without tax)
{
double cost = 0.0;
double weight = 0.0;
int days = 0;
cost = 0.7;
return totalFee = cost * weight * days;
}//end dogTotalFee
public static double dogTax(double totalTax)//calculate tax
{double taxRate = 0.0;
double totalFee = 0.0;
return totalTax = totalFee * taxRate;
}//end dogTax
public static double dogTotalPrice(double totalPrice)
{
double totalFee = 0.0;
double totalTax = 0.0;
return totalPrice = totalFee + totalTax;
}//end dogTotalPrice
These values show up as zero, and the calculations don't add up.
totalFee = dogTotalFee(totalFee);
totalTax = dogTax(totalTax);
totalPrice = dogTotalPrice(totalPrice);
lPrice);
I'm mostly doing the math in the methods, I just can't seem to get the values to transfer. Thank you

How to print variable

In my code I need to print out the tax variable. It's not working and I think I know why I just don't know how to do it. I need to initialize the variable tax but I don't know how to in a main class. Here is my code.
System.out.println("Enter your income!");
double income = scan.nextDouble();
if (income < 50000)
{
double tax = income / 100;
}
else if (income < 75000)
{
double tax = income / 100 * 2;
}
else if (income < 100000)
{
double tax = income / 100 * 3;
}
else if (income < 250000)
{
double tax = income / 100 * 4;
}
else if (income < 500000)
{
double tax = income / 100 * 5;
}
else if (income > 500000)
{
double tax = income / 100 * 6;
}
double tax = 0.0;
This line should be above the rest of your code. Then in your if statements remove the declarations of tax and instead just assign your expressions to tax:
tax = income / 100 * some number;
What is happening in your code right now is that there is a different tax variable for each else if statement you have, and because of the behavior of scope in java the program can only see the tax variable inside the else if that it is declared in. For example:
if(condition){
double tax = number;
}
else if(condition){
double tax = number;
}
else{
double tax = number;
}
This code block is similar to what you have. The tax variables in this code block can only be used inside their respective code blocks. Only between the curly braces does each tax variable exist. Once you leave the curly braces that variable no longer exists. It is deleted by java. Then when you reach the next set of curly braces and declare tax anew it is an entirely different variable as compared to this code
function(){
double tax = 0.0;
if(condition){
tax = number;
}
else if(condition){
tax = number;
}
else{
tax = number;
}
}
tax is the same variable throughout the if statements here because it exists between the curly braces of the function and not only between the curly braces of an if statement because it was declared outside the if statements.

My Java program is outputting the wrong answer when finding tax for a salary

There is no tax on the first 20% of salary entered. i.e for 20000..it would tax for 16000 with 10% on 15000 and 20% on the remaining 1000 which would be 1700 total tax. My program incorrectly outputs 14500....
import java.util.*;
public class taxable {
public static void main (String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter your salary:");
double salary=in.nextDouble();
double taxDue=0;
double tempTaxDue=0;
if (salary < 15000) {
System.out.println("No tax applicable");
}else if
(salary >=15000 && salary <20000) {
taxDue=(15000*0.1);
}else if
(salary >=20000 && salary <=35000) {
tempTaxDue=(salary*0.8);
taxDue=15000*0.1+tempTaxDue-15000*0.2;
}else if
(salary > 35000) {
tempTaxDue=salary*0.8;
taxDue=(15000*0.1)+(20000*0.2)+(tempTaxDue-35000*0.35);
taxDue=(salary*0.8)+(20000*0.2)+(salary-35000*0.35);
}
System.out.printf("The amount of tax due is: " + taxDue + " ");
double avTaxRate;
avTaxRate=taxDue/salary*100;
System.out.printf("The average tax rate: " + avTaxRate + "%%");
}
}
When dividing integer values, always check for floating point division - 10/100 will be 0 by Java integer division terms, 10.0/100 circumcises this.
To get 10% out of something either divide it by 10.0 or multiply by 0.1.
taxDue = 15000 * 0.1;
But the biggest hidden problem here is you shouldn't use double to represent money. Use BigDecimal instead.
Why? Just for fun, let's calculate the 10% taxes over 15001?
double dValue = 15001;
double dTaxes = 15001 * 0.1;
System.out.println("Taxes with double: " + dTaxes);
// Taxes with double: 1500.1000000000001
Precision error -> Small, but it is there 0.0000000000001.
BigDecimal to the rescue:
BigDecimal value = new BigDecimal("15001");
BigDecimal taxes = value.multiply(new BigDecimal("0.1"));
System.out.println("Taxes with BigDecimal: " + taxes);
// Taxes with BigDecimal: 1500.1
Working example.
You have to use casting when you trying to assign to double variable some division, instead:
taxDue=15000*(10/100);
smt as make one of divisor double value:
taxDue = 15000.0 * (10.0 / 100);

Categories

Resources