How to round my output in a tax program [Java]? [duplicate] - java

This question already has answers here:
How to round a number to n decimal places in Java
(39 answers)
Closed 8 years ago.
I need my output to float to only 2 decimal places as the output is money. For example if I run:
Enter 1 if you are single. Enter 2 if you are married
1
Enter your taxable income
27060.34
Federal Income Tax:$4060.3435
I need the federal income tax to output $4060.34 instead of $4060.3435
My code:
import static org.junit.Assert.*;
import java.util.Scanner;
import org.junit.Test;
public class IRS {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter 1 if you are single. Enter 2 if you are married");
int martialstatus = scan.nextInt();
if (martialstatus == 1) {
Scanner scan2 = new Scanner(System.in);
System.out.println("Enter your taxable income");
double income = scan2.nextDouble();
if ((income > 0) && (income <= 27050.00)) {
System.out.println("Federal Income Tax:$" + (income * .15));
}
if ((income > 27050.00) && (income <= 65550.00)) {
System.out.println("Federal Income Tax:$" + (4057.50 + (.275 * (income - 27050))));
}
if ((income > 65550.00) && (income <= 136750.00)) {
System.out.println("Federal Income Tax:$" + (14645.00 + (.305 * (income - 65550.00))));
}
if ((income > 136750.00) && (income <= 297350.00)) {
System.out.println("Federal Income Tax:$" + (36361.00 + (.355 * (income - 136750.00))));
}
if (income > 297350.00) {
System.out.println("Federal Income Tax:$" + (93374.00 + (.391 * (income - 297350.00))));
}
} else if (martialstatus == 2) {
Scanner scan3 = new Scanner(System.in);
System.out.println("Enter your taxable income");
double income2 = scan3.nextDouble();
if (income2 <= 45200.00) {
System.out.println("Federal Income Tax:$" + (.15 * income2));
}
if ((income2 > 45200.00) && (income2 <= 109250.00)) {
System.out.println("Federal Income Tax:$" + (6780.00 + (.275 * (income2 - 45200))));
}
if ((income2 > 109250.00) && (income2 <= 166500.00)) {
System.out.println("Federal Income Tax:$" + (24393.75 + (.305 * (income2 - 109250.00))));
}
if ((income2 > 166500.00) && (income2 <= 297350.00)) {
System.out.println("Federal Income Tax:$" + (41855.00 + (.355 * (income2 - 166500.00))));
}
if (income2 > 297350.00) {
System.out.println("Federal Income Tax:$" + (88306.00 + (.391 * (income2 - 297350.00))));
}
} else {
System.out.println("Error. Try again");
}
}
}

If you are comfortable with C style printing (which is very much what I'd recommend here) you can use System.out.printf() which is very similar to C's printf().
System.out.printf ("Federal Income Tax: $%.2f", federalTax);

Due to the inherent uncertainty involved with floating point arithmetic, you should always use BigDecimal for mathematical operations where knowing you have the "right" answer is important (tax program would be a good example where that's important).
This question has a good example, take good note of the first answer:
Using BigDecimal to work with currencies

First of all: don't use float or double to calculate with currency values. Use BigDecimal instead.
Second to your question:
To round a value use the following formula (I use double in my example but don't do this if you do not know what you're doing):
public double round(double value) {
return (((int)(value * 10.d))/10.d);
}
This method rounds to one valid decimal place. You have to change this implementation if you want another number of decimal places.

Use DecimalFormat:
java.text.DecimalFormat formatter = new java.text.DecimalFormat( "$###,###,###,##0.00";-$###,###,###,##0.00" );
formatter.format( 4060.3435 );

System.out.println("Federal Income Tax:$" + (double) Math.round((88306.00 +(.391*(income2 - 297350.00))))) /100.0;

As others have said: Either use BigDecimal or -- the better solution in most cases -- do your calculations in pennies rather than dollars. That gets rid of most of the round-off issues immediately!

Related

My program is printing the error message twice when a char is entered, how to do I print only once when the char is entered?

I am building a program that checks your salary and returns the amount of tax that you will pay for that financial year.
When the user inserts a character instead of an int, the code below prints the error message twice. How do I change that so it only prints the message once.
Any help would be appreciated. I know the error is occurring in the if statement but I do not know how to change it to detect that the input from user is a char or not.
/* this code works bar one thing with
1: When a Char is entered, it prints an error message twice - doesn't do this when a negative number is entered.
*/
import java.util.Scanner;
public class MyProgram {
public static void main(String[] args) {
// call scanner for user input
Scanner in = new Scanner(System.in);
// double for salary
int salary = 0;
double incomeTax = 0;
double weeklyIncome;
do {
System.out.println("Please enter your salary?");
try {
salary = in.nextInt();
// test if user enters something other than an integer
} catch (java.util.InputMismatchException e) {
System.out.println("Invalid input, only enter a number");
salary = Integer.MIN_VALUE; in.next(); // consume the non-int so we don't get caught in an endless loop\
}
if (salary <= 0) {
System.out.println("Invalid input, please enter a number above 0");
}
}
while (salary <= 0); // loop as long as the salary is less than zero
if (salary <= 18000 & salary > 0) {
incomeTax = 0;
System.out.println("your salary is $" + salary + ", you will pay no income tax this financial year.");
} else if (salary >= 18201 & salary <= 45000) {
incomeTax = (0.19 * (salary - 18200));
weeklyIncome = (salary/52);
System.out.println("your weekly income is $" + weeklyIncome);
System.out.println("you will pay $" + incomeTax + " in tax this financial year.");
} else if (salary >= 45001 & salary <= 120000) {
incomeTax = 5062 + (0.325 * (salary - 45000));
weeklyIncome = (salary/52);
System.out.println("your weekly income is $" + weeklyIncome);
System.out.println("you will pay $" + incomeTax + " in tax this financial year.");
} else if (salary >= 120001 & salary <= 180000) {
incomeTax = 29467 + (0.37 * (salary - 120000));
weeklyIncome = (salary/52);
System.out.println("your weekly income is $" + weeklyIncome);
System.out.println("you will pay $" + incomeTax + " in tax this financial year.");
} else if (salary >= 180001) {
incomeTax = 51667 + (0.45 * (salary - 180000));
weeklyIncome = (salary/52);
System.out.println("your weekly income is $" + weeklyIncome);
System.out.println("you will pay $" + incomeTax + " in tax this financial year.");
}
in .close();
}
}

Trying to multipy but its only multiplying .10 to any input I type in. Also for my Scanner "resource" says its never closed [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I am working on this "if else" statement to multiply a range of numbers but it only multiplies to .10
Not sure what I am doing wrong. Additionally for "resource" it says its never closed.
import java.util.Scanner;
public class taxableIncome {
public static void main(String[] args){
{
Scanner resource = new Scanner(System.in); //scanner object for keyboard input.
System.out.print("Enter annual income: ");
{
int input = 0;
double ten = .10; // 10% tax
double fifthteen = .15; // 15% tax
double twentyfive = .25;
double twentyeight = .28;
double thirtythree = .33;
double thirtyfive = .35;
double total = 0.0;
boolean taxes = true;
while(taxes)
{
if (input >= 0 && input <= 8500){
total = ten * resource.nextDouble();
System.out.println("The taxable annual income is $" + total + "\nThank you very much.");
}else if (input >= 8500 && input <= 34500){
total = fifthteen * resource.nextDouble();
System.out.println("The taxable annual income is $" + total + "\nThank you very much.");
} else if (input >= 34500 && input <= 83600){
total = twentyfive * resource.nextDouble();
System.out.println("The taxable annual income is $" + total + "\nThank you very much.");
}else if (input >= 83600 && input <= 174400){
total = twentyeight * resource.nextDouble();
System.out.println("The taxable annual income is $" + total + "\nThank you very much.");
}else if (input >= 174400 && input <= 379150){
total = thirtythree * resource.nextDouble();
System.out.println("The taxable annual income is $" + total + "\nThank you very much.");
}else if (input >= 379150 && input >= 379151) {
total = thirtyfive * resource.nextDouble();
System.out.println("The taxable annual income is $" + total + "\nThank you very much.");
taxes = false;
}
}
}
}
}
}
Your code is always evaluating for input == 0.0 because at no point does the code update this value. The program also never terminates for this reason as well.
Your input variable is initialized to 0.0, therefore it will always enter the first if statement and multiply by 0.10.
Take the salary input out of the if statements so the if statements will check based on your inputs.

If-else statements made my program stop immediately -- Java

I'm just going to post what I've got so far in a program that is supposed to do the following:
- Calculate BAC (blood alcohol content) based on inputs given by the user and determine, with the various inputs, whether or not they would get a DUI (be over the limit based on inputs given).
So here's my code:
import java.util.*;
public class Proj2_Mazzone
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
String gender;
int D, W, H, age;
double ratio, limit, alcAbsorbed, alcMetabolized, BAC;
...
//BAC is calculated here, based on given input
//Make 4 diff scenarios using && with if statements...
//So f21, fnot21, m21, mnot21
System.out.print("Enter M if you're a male, or F if you're a female: ");
gender = scan.nextLine();
//males over 21
if(gender.equalsIgnoreCase("m") && age > 21){
ratio = .73;
limit = .08;
alcAbsorbed = (3.701 * D) / (W * ratio);
alcMetabolized = .015 * H;
BAC = alcAbsorbed - alcMetabolized;
if(BAC >= limit){
System.out.println("You're over the limit!");
System.out.println("Your BAC is " + BAC + "!");
}
else if(BAC <= limit){
System.out.println("You're good...for now.");
System.out.println("Your BAC is " + BAC + ".");
}
}
//males under 21
if(gender.equalsIgnoreCase("m") && age < 21){
ratio = .73;
limit = .02;
alcAbsorbed = (3.701 * D) / (W * ratio);
alcMetabolized = .015 * H;
BAC = alcAbsorbed - alcMetabolized;
if(BAC >= limit){
System.out.println("You're over the limit!");
System.out.println("Your BAC is " + BAC + "!");
}
else if(BAC <= limit){
System.out.println("You're good...for now.");
System.out.println("Your BAC is " + BAC + ".");
}
}
//females over 21
if(gender.equalsIgnoreCase("f") && age > 21){
ratio = .66;
limit = .08;
alcAbsorbed = (3.701 * D) / (W * ratio);
alcMetabolized = .015 * H;
BAC = alcAbsorbed - alcMetabolized;
if(BAC >= limit){
System.out.println("You're over the limit!");
System.out.println("Your BAC is " + BAC + "!");
}
else if(BAC <= limit){
System.out.println("You're good...for now.");
System.out.println("Your BAC is " + BAC + ".");
}
}
//females under 21
if(gender.equalsIgnoreCase("f") && age < 21){
ratio = .66;
limit = .02;
alcAbsorbed = (3.701 * D) / (W * ratio);
alcMetabolized = .015 * H;
BAC = alcAbsorbed - alcMetabolized;
if(BAC >= limit){
System.out.println("You're over the limit!");
System.out.println("Your BAC is " + BAC + "!");
}
else if(BAC <= limit){
System.out.println("You're good...for now.");
System.out.println("Your BAC is " + BAC + ".");
}
}
...
It may not be the best way to do it, but any help is appreciated. Thanks in advance.
The real problem in the else if statements is that one of them may not trigger. Instead of doing an if else if statement in the if(BAC<=limit), do something like:
if (BAC >= limit) {
System.out.println("You're over the limit!");
System.out.println("Your BAC is " + BAC + "!");
} else {
System.out.println("You're good...for now.");
System.out.println("Your BAC is " + BAC + ".");
}
Also, do you ever read the age in you program?
Rather than writing same code again and again you should create one common function. That will take 2 arguments that is ratio and limit.
Apart from this all other calculations are common for all age limits and male or female.
Do your calculation in that function and simply print it
it will shorten your code and will make it more readable and understandable.
There's a logic problem: 21 year old females fall through. Your main ifs are:
if(gender.equalsIgnoreCase("f") && age > 21){
...
}
if(gender.equalsIgnoreCase("f") && age < 21){
....
}
If the age is exactly 21, neither block will be entered.
Your problem comes from the fact that your conditions are wrong for a women who is 21 year old! She's excluded from all the cases.
Also your code is hard to debug because it's hard to read.
Consider the following refactoring where I created methods to determine the values.
I went very far for a simple code like that but it's to show you that you should never copy/paste code. When you repeat code, it means that you can put it in a method that will be called several times with the right arguments.
public class StackOverflow {
// TODO define the real values!
private static final int D = 0, W = 0, H = 0;
public static void main(String[] args) {
// Get the input
Scanner scan = new Scanner(System.in);
System.out.print("Enter M if you're a male, or F if you're a female: ");
String gender = scan.nextLine();
System.out.print("Enter your age: ");
int age = Integer.valueOf(scan.nextLine());
// Get the good values
double ratio = getRatio(gender);
double bac = getBAC(ratio);
double limit = getLimit(age);
// Print the result
if (bac <= limit) {
System.out.println("You're good...for now.");
} else {
System.out.println("You're over the limit!");
}
System.out.println("Your BAC is " + bac + "!");
}
/**
* This method returns the ratio according to the gender.
*/
private static double getRatio(String gender) {
if ("m".equalsIgnoreCase(gender)) {
return .73;
} else if ("f".equalsIgnoreCase(gender)) {
return .66;
}
throw new IllegalArgumentException("Unknown gender: " + gender);
}
/**
* This method returns the BAC according to the ratio.
*/
private static double getBAC(double ratio) {
double alcAbsorbed = (3.701 * D) / (W * ratio);
double alcMetabolized = .015 * H;
return alcAbsorbed - alcMetabolized;
}
/**
* This method returns the limit according to the age.
*/
private static double getLimit(int age) {
if (age < 21) {
return .02;
} else {
return .08;
}
}
}
I would recommend to refactor this code after you've found the problem to reduce duplication. Also try to avoid if-statements that may cause no code to be run, instead use an if-else statement - You always want to print something, otherwise it feels as the program just stops.
Perhaps something like this
public static void main (String[] args)
{
// Scan variables etc
// calculate ratio
double ratio = -1;
if (gender.equalsIgnoreCase("m"))
{
ratio = .73;
}
if (gender.equalsIgnoreCase("f"))
{
ratio = .66;
}
// calculate limit
double limit = -1
if (age > 21)
limit = .08;
limit = .02;
// calculate blood alcohol level
alcAbsorbed = (3.701 * D) / (W * ratio);
alcMetabolized = .015 * H;
double bloodAlcoholLevel = alcAbsorbed - alcMetabolized;
if(bloodAlcoholLevel >= limit)
{
System.out.println("You're over the limit!");
System.out.println("Your BAC is " + BAC + "!");
}
else
{
System.out.println("You're good...for now.");
System.out.println("Your BAC is " + BAC + ".");
}
}
This way your code can be much shorter and easier to read, not to mention change. :-)

find income tax based on annual income and marital status - java program

I'm not sure what the issue is. The top of the console says after the user inputs annual income. There are no errors shown in the console itself.
The program is to find income tax based on annual income and marital status.
This is my code:
import java.util.Scanner;
public class taxpayers {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String maritalStatus;
System.out.println("What is your marital status? Type 'M' for married and 'S' for single.");
maritalStatus = sc.next(); //reads next input as marital status
System.out.println("What is your annual income?");
double income;
income = sc.nextDouble();
double marriedTax; //declare these doubles before beginning the if/then statements
double singleTax;
if (maritalStatus.equals("M")) {
just small syntax error
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String maritalStatus;
System.out.println("What is your marital status? Type 'M' for married and 'S' for single.");
maritalStatus = sc.next(); //reads next input as marital status
System.out.println("What is your annual income?");
double income;
income = sc.nextDouble();
double marriedTax = 0; //declare these doubles before beginning the if/then statements
double singleTax;
if (maritalStatus.equals("M")) {
if (income > 0 && income <= 39000) {
marriedTax = income * .15;
}
else if (income > 39000 && income <= 94250) {
marriedTax = (income - 39000) * .28 + 5850;
}
else if (income > 94250 && income <= 143600) {
marriedTax = (income - 94250) * .31 + 21320;
}
else if (income > 143600 && income <= 256500) {
marriedTax = (income - 143600) * .36 + 36618.5;
}
else if (income > 256500) {
marriedTax = (income - 256500) * 39.6 + 77262.5;
}
System.out.printf("Your income taxes are $%.2f.", marriedTax );
};
if (maritalStatus.equals("S")) {
if (income > 0 && income <= 23350) {
singleTax = income * .15;
}
else if (income > 23350 && income <= 56550) {
singleTax = (income - 23350) * .28 + 3502.5;
}
else if (income > 56550 && income <= 117950) {
singleTax = (income - 56550) * .31 + 12798.5;
}
else if (income > 117950 && income <= 256500) {
singleTax = (income - 117950) * .36 + 31832.5;
}
else if (income > 256500); {
singleTax = (income - 256500) * 39.6 + 81710.5;
}
System.out.printf("Your income taxes are $%.2f.", singleTax);
};
sc.close();
}
Your last else if conditions are incorrect
else if (income > 256500); <-- this end the condition
else if (income > 256500); <-- this end the condition
Remove semicolns at the end and use {
try like this
public class taxpayers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String maritalStatus;
System.out.println("What is your marital status? Type 'M' for married and 'S' for single.");
maritalStatus = sc.next(); //reads next input as marital status
System.out.println("What is your annual income?");
double income;
income = sc.nextDouble();
double marriedTax; //declare these doubles before beginning the if/then statements
double singleTax;
if (maritalStatus.equals("M")) {
if (income > 0 && income <= 39000) {
marriedTax = income * .15;
} else if (income > 39000 && income <= 94250) {
marriedTax = (income - 39000) * .28 + 5850;
} else if (income > 94250 && income <= 143600) {
marriedTax = (income - 94250) * .31 + 21320;
} else if (income > 143600 && income <= 256500) {
marriedTax = (income - 143600) * .36 + 36618.5;
} else if (income > 256500){
marriedTax = (income - 256500) * 39.6 + 77262.5;
}
System.out.printf("Your income taxes are $%.2f.", marriedTax);
};
if (maritalStatus.equals("S")) {
if (income > 0 && income <= 23350) {
singleTax = income * .15;
} else if (income > 23350 && income <= 56550) {
singleTax = (income - 23350) * .28 + 3502.5;
} else if (income > 56550 && income <= 117950) {
singleTax = (income - 56550) * .31 + 12798.5;
} else if (income > 117950 && income <= 256500) {
singleTax = (income - 117950) * .36 + 31832.5;
} else if (income > 256500){
singleTax = (income - 256500) * 39.6 + 81710.5;
}
System.out.printf("Your income taxes are $%.2f.", singleTax);
}
sc.close();
}
}

Java, subtracting double data type

I am trying to do a simple calculation. I can't figure out how to subtract "double admissionPrice" in the last if-else statements.
Its pointing to the subtraction sign giving me this error message:
operator - cannot be applied to java.lang.String,double
Please help. thanks.
import java.text.*;
import java.util.Scanner;
class IMC {
public static void main(String[] args) {
int numEmployees = 0;
double costPerAttendee = 0.00;
int employeeDiscount;
double admissionPrice = 0.00;
Scanner keyboard = new Scanner (System.in);
System.out.print("Enter amount of employees attending: ");
numEmployees = keyboard.nextInt();
System.out.print("Have any employees attended previously? \n For: YES=1 or NO=2"
);
employeeDiscount = keyboard.nextInt();
if (numEmployees == 1) { admissionPrice = 695.00;
} else if (numEmployees == 2 || numEmployees == 3 ||numEmployees == 4) { admissionPrice = 545.00;
} else if (numEmployees >= 5 ||numEmployees >= 6 ||numEmployees >= 7 ||numEmployees >= 8){ admissionPrice = 480.00;
} else if (numEmployees >= 9) { admissionPrice = 395.00;
}
System.out.print("The cost per attendee is: " + admissionPrice );
if (employeeDiscount == 1){
System.out.print("Total price after discount (15%) is : " + admissionPrice - (admissionPrice * 0.15) );
} else if (employeeDiscount == 2) {
System.out.print("No discount. Total price is still: " + admissionPrice);
}
}
}
Place parenthesis around (admissionPrice - (admissionPrice * 0.15) ). Right now, it concatenates admissionPrice on to "Total price after discount (15%) is : " before attempting subtraction.
The + operator in your println() statement is taking precedence and converting admissionPrice to a String.
Put your arithmetic operation in parenthesis.
System.out.print("Total price after discount (15%) is : " + (admissionPrice - (admissionPrice * 0.15)));
^ ^
You need to add () to fix the precedence, else, as the error indicates, you are subtracting, not from admissionPrice but the string that is formed of "To....:" + admissionPrice

Categories

Resources