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.
Related
I am getting a NaN error when I compile this, i can't figure out what I am doing wrong? I tried moving the variables around to see if I could get them working but nothing. Notice the variable I put of type double i used for bmi after inches = keyboard.nextInt(); I think its a divide by zero error but i dont know what i am dividing by zero.
import java.util.Scanner;
public class BodyMassIndex {
public static void main(String[] args) {
// TODO Auto-generated method stub
int pounds =0;
int feet = 0;
int inches = 0;
double heightMeters = ((feet * 12) + inches) * .0254;
double mass = pounds / 2.2;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter your weight in pounds");
pounds = keyboard.nextInt();
System.out.println("Enter how many feet you are");
feet = keyboard.nextInt();
System.out.println("Enter how many inches after feet");
inches = keyboard.nextInt();
double bmi = mass / (heightMeters * heightMeters);
System.out.println(mass);
System.out.println(bmi);
if(bmi < 18.5){
System.out.println("Underweight");
}
else if ((bmi >= 18.5) && (bmi < 25)){
System.out.println("Normal weight");
}
else if ((bmi >= 25) && (bmi < 30))
System.out.println("Above weight");
else
System.out.println("Obese");
}
}
It's important to understand the dynamic nature of your variables, such that when you type
double heightMeters = ((feet * 12) + inches) * .0254;
This assignment is immediately evaluated using the current values of feet and inches (which are 0 at that moment), before any of the keyboard entry is performed. To perform these calculations with the values entered by the keyboard, these calculations need to be performed and their results assigned to their corresponding variables after the keyboard entry is done, when the current values of pounds, feet and inches are what you just entered. Because heightMeters is still zero from its initialization and hasn't been changed since, you're getting a divide by zero.
You're getting the exception because the value of heightMeters is 0 here:
double bmi = mass / (heightMeters * heightMeters);
The only time that heightMeters is calculated, the result of it is 0:
double heightMeters = ((feet * 12) + inches) * .0254;
It looks like you want to use this calculation, so I'd split it into a separate function:
public static double getHeightInMeters(int feet, int inches)
{
return 0.0254 * ((feet * 12) + inches);
}
Then you can call it later:
double heightMeters = this.getHeightInMeters(feet, inches);
double bmi = mass / (heightMeters * heightMeters);
The tax depends on how far apart their salaries are. If the salaries are within $10,000 of each other, the tax is 5% of the total. If they are more than $10,000 apart, the tax is 5% of the larger income plus 3% of the smaller one.
Can someone explain what I'm doing wrong with my if statements that isn't letting the test pass.
public double spouseDistance(double income1, double income2)
{
double tax;
double totalincome = income1 + income2;
double incomedistance = income1 - income2;
if (incomedistance > 10000)
{
if(income1 > income2)
{
tax = income1 * 0.05 + income2 * 0.03;
}else
{
tax = income2 * 0.05 + income1 * 0.03;
}
}
else
{
tax = totalincome * 0.05;
}
return tax;
}
}
#Test
public void testSpousesDistance()
{
TaxCalculator tc = new TaxCalculator();
// The border case here is when the difference between the
// salaries is 10,000 and the value changes at 10,000.01.
// Since the order of the parameters shouldn't matter, do
// both cases with both parameter orders
assertEquals(40000*0.05, tc.spouseDistance(25000,15000), 0.001);
assertEquals(40000*0.05, tc.spouseDistance(15000,25000), 0.001);
assertEquals(30000.01*0.05 + 20000*0.03,tc.spouseDistance(20000.00,30000.01), 0.001);
assertEquals(30000.01*0.05 + 20000*0.03,tc.spouseDistance(30000.01, 20000.00), 0.001);
}
}
You want to set incomeDistance to Math.abs(income1 - income2) to get the absolute value of the difference. The way you have it, if income2 > income1 you branch to the wrong block of code.
Take your 20,000 and 30,000.01 example. At that point incomeDistance become 20,000-30,000.01, or -10,000, which is less than 10,000.
You have to make sure that the result of the incomedistance is not negative. Because if income 2 is greater than income one, in your code, the result will appear negative.
If the result is negative, multiply the result by (-1) if you don't
want to include an entire library just for a single purpose.
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);
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.
I have done a google around but can't get my head around what's wrong with my code here.
I'm getting an Illegal start of expression error in the if statement at the first 'Else if'
I'm pretty new to Java but trying to quickly learn as its a requirement of my computing course I'm hoping to do.
Any help greatly appreciated.
import java.util.Scanner;
public class net_salary{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
int income;
int incometax;
int afterincometax;
int nationalinsurance;
int afterni;
int pension;
income = in.nextInt();
if(income = 0) {
incometax = 0;
} else if (income >=9000 & <=21000) {
incometax = income * 0.15;
} else if (income >=21000 & <=31000) {
incometax = income * 0.2;
} else if (income >=31000 & <=50000) {
incometax = income * 0.225
You need else if (income >=9000 && income <=21000) instead of else if (income >=9000 & <=21000).
Similarly for the other else if expressions.
You have to make two separate comparisons to income. You can't say "if income is greater than or equal to 9000 or less than or equal to 21000". You must say "if income is greater than 9000 or income is less than or equal to 21000".
& is a bitwise AND. && is logical AND.
As stated by others, income = 0 should read income == 0.
You need && not &, and repeat the variable 'income' :
else if (income >=9000 && income <=21000)
You are also using = where you probably mean ==
if(income == 0)
= assigns a value, == tests whether two values are equal.
Your if/else if block expression always should results as boolean (either true/false). In Java, && represents AND, & is bitwise operator which manipulates bits.
if(income == 0)
{
incometax = 0;
}
**else if (income >=9000 && income <=21000)**
{
incometax = income * 0.15;
}
else if (income >=21000 && income <=31000)
{
incometax = income * 0.2;
}
else if (income >=31000 && income <=50000)
{
incometax = income * 0.225
if(income = 0)
should be
if(income == 0)
and
else if (income >=9000 & <=21000)
(and it's followers) should be
else if (income >=9000 && income <=21000)
and looks like you you need to make some of your variables double instead of int.
Check the usage of "=", "==", "&", "&&" operators in Java.
public class net_salary{
public static void main(String[]args){
int income, ncometax, afterincometax, nationalinsurance, afterni, pension;
Scanner in = new Scanner(System.in);
income = in.nextInt();
if(income == 0) {
incometax = 0;
} else if (income >= 9000 && income <= 21000) {
incometax = income * 0.15;
} else if (income >=21000 && income <= 31000) {
incometax = income * 0.2;
} else if (income >=31000 && income <= 50000) {
}
}
}