just need help with formatting a string to look like this:
Here is your tax breakdown:
Income $25,000.00
Dependants 1
----------------------------
Federal Tax $4,250.00
Provincial Tax $1,317.75
============================
Total Tax $5,567.75"
heres my code, please help me format as above with spaces and decimals
import java.util.Scanner;
public class HelloWorld {
public static void main(String args[]) {
double income, fedTax, provTax;
int dependents;
Scanner input = new Scanner(System.in);
System.out.print("Please enter your taxable income: ");
income = input.nextInt();
System.out.println();
System.out.print("Please enter your number of dependents: ");
dependents = input.nextInt();
System.out.println();
if (income <= 29590) {
fedTax = 0.17 * income;
}
else if (income <= 59179.99) {
fedTax = 0.17 * 29590 + 0.26 * (income - 29590);
}
else {
fedTax = 0.17 * 29590 + 0.26 * 29590 + (0.29 * (income - 59180));
}
double base = 42.5 * fedTax;
double deductions = 160.50 + 328 * dependents;
provTax = base - deductions;
if (base < deductions) {
provTax = 0;
}
else {
provTax = base - deductions;
}
double totalTax = fedTax + provTax;
System.out.println("Here is your tax breakdown: ");
System.out.println(String.format(" Income%,10.d", income));
System.out.println(String.format(" Dependants%10.d", dependents));
System.out.println("-------------------------");
System.out.println(String.format(" Federal Tax%,10.2f", fedTax));
System.out.println(String.format("Provincial tax%,10.2f", provTax));
System.out.println("=========================");
System.out.println(String.format(" Total Tax%,10.2f", totalTax));
}
}
please ignore down here this is just to let me post because there isnt enough words, even though my question does not to be detailed :(
If the income variable is declared a double data type then you can't expect to fill that variable using the Scanner#nextInt() method which is expecting the User to enter an Integer value whereas you want to enter a double (floating point) value. At the very least you want to use the Scanner#nextDouble() method.
I don't think your calculations for Provincial Tax is correct. If it is then I sure wouldn't want to deal with that bill. I'm not going to try and figure that one out but this is rather suspect to start with:
double base = 42.5 * fedTax;
double deductions = 160.50 + 328 * dependents;
provTax = base - deductions; // deductions removed from base here...
if (base < deductions) {
provTax = 0;
}
else {
provTax = base - deductions; // and yet again here....hmmmm
}
To get the formatting you want you would want to possibly utilize both the String#format() method along with the DecimalFormat#format() method and possibly a couple of its' other methods (read end note), for example:
// Set the numerical format you want.
java.text.DecimalFormat decimalFormat = new java.text.DecimalFormat("0.00");
decimalFormat.setGroupingUsed(true); // You want comma grouping
decimalFormat.setGroupingSize(3); // Comma every 3 digits
System.out.println("Here is your tax breakdown: ");
System.out.println(String.format("Income %20s", "$" + decimalFormat.format(income)));
System.out.println(String.format("Dependants %16d", dependents));
System.out.println("---------------------------");
System.out.println(String.format("Federal Tax %15s", "$" + decimalFormat.format(fedTax)));
System.out.println(String.format("Provincial Tax %12s", "$" + decimalFormat.format(provTax)));
System.out.println("===========================");
System.out.println(String.format("Total Tax %17s", "$" + decimalFormat.format(totalTax)));
Your entire code with the above modification and the fix for the income prompt (using the Scanner#nextDouble() method) would look something like this:
double income, fedTax, provTax;
int dependents;
Scanner input = new Scanner(System.in);
System.out.print("Please enter your taxable income: ");
income = input.nextDouble();
System.out.println();
System.out.print("Please enter your number of dependents: ");
dependents = input.nextInt();
System.out.println();
if (income <= 29590) {
fedTax = 0.17 * income;
}
else if (income <= 59179.99) {
fedTax = 0.17 * 29590 + 0.26 * (income - 29590);
}
else {
fedTax = 0.17 * 29590 + 0.26 * 29590 + (0.29 * (income - 59180));
}
double base = 42.5 * fedTax;
double deductions = 160.50 + 328 * dependents;
provTax = base - deductions;
if (base < deductions) {
provTax = 0;
}
else {
provTax = base - deductions;
}
double totalTax = fedTax + provTax;
// Set the numerical format you want.
java.text.DecimalFormat decimalFormat = new java.text.DecimalFormat("0.00");
decimalFormat.setGroupingUsed(true); // You want comma grouping
decimalFormat.setGroupingSize(3); // Comma every 3 digits
System.out.println("Here is your tax breakdown: ");
System.out.println(String.format("Income %20s", "$" + decimalFormat.format(income)));
System.out.println(String.format("Dependents %16d", dependents));
System.out.println("---------------------------");
System.out.println(String.format("Federal Tax %15s", "$" + decimalFormat.format(fedTax)));
System.out.println(String.format("Provincial Tax %12s", "$" + decimalFormat.format(provTax)));
System.out.println("===========================");
System.out.println(String.format("Total Tax %17s", "$" + decimalFormat.format(totalTax)));
If you were to run this code now, you should see in the Console Window the following (if you supply the same values):
Please enter your taxable income: 25500.54
Please enter your number of dependents: 1
Here is your tax breakdown:
Income $25,500.54
Dependents 1
---------------------------
Federal Tax $4,335.09
Provincial Tax $183,752.90
===========================
Total Tax $188,087.99
What a tax bill for 25.5 grand. :/
Note: You can eliminate the use of the DecimalFormat#setGroupingUsed() and the DecimalFormat#setGroupingSize() methods if you initialize your decimalformat variable with:
DecimalFormat decimalFormat = new DecimalFormat("#,###,##0.00");
Related
This is my first class and first time using Java. I also need to display 'Employee Name, Rate of Pay, Hours Worked, Overtime Worked, Gross Pay, Total amount of deductions, & Net Pay in the program as well.
package calculatepayprogram;
import java.util.Scanner;
/**
* Calculate Pay Program
* CPT 307: Data Structures & Algorithms
* 7/5/2022
*/
public class CalculatePayProgram{
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
double RateOfPay;
int HoursWorked;
double GrossPay;
double OvertimeHours;
double OvertimePay;
double NetPay;
double TotalDeductions;
String name;
System.out.println("Enter Your Name: ");
name = reader.nextLine();
System.out.print("Enter Your Pay Per Hour: ");
RateOfPay = reader.nextDouble();
System.out.print("Enter Your Hours Worked: ");
HoursWorked = reader.nextInt();
System.out.print("Enter Your Overtime Hours Worked: ");
OvertimeHours = reader.nextDouble();
GrossPay = RateOfPay * HoursWorked;
OvertimePay = OvertimeHours * 1.5 * RateOfPay;
double Pay = OvertimePay + GrossPay;
System.out.println("Your Gross Pay For This Week Will Be $" + Pay);
double FederalTax = .15 * Pay;
double StateTax = .0307 * Pay;
double Medicare = .0145 * Pay;
double SocialSecurity = .062 * Pay;
double Unemployment = .0007 * Pay;
double TotalDeduct = FederalTax + StateTax + Medicare + SocialSecurity + Unemployment;
System.out.println("Your Total Deductions For This Week Will Be $" + TotalDeduct);
NetPay = Pay - TotalDeduct;
System.out.println("Your Net Pay For This Week Will Be $" + NetPay);
}
}
Part of the requirement is to replicate the bar graph in https://imgur.com/a/Gx2XOql
I tried this to see if I could rectangle in the dialogue window (obviously it didn't work):
rectMode(CENTER);
// Alberta
if ( prov_id.equals("AB") || prov_id.equals("ab"))
{
if (gross_income>=0&&gross_income<=40000)
{
tax_rate=0.25;
JOptionPane.showMessageDialog(frame,"Province: "+ prov_id + "\nGross Income: "+ gross_income + "\nTax Rate: "+ tax_rate+ "\nTax Amount: "+ tax_amount+"\nNet Income: "+ net_income + rect(10,10,10,10));
}
The rest of my code:
import javax.swing.JOptionPane;
//Input Variables
String prov_id = ""; //province_id will contain the user input for the province (E.g. 'AB').
float gross_income = 0; //gorss_income contains the user input for gross income (E.g. 30000).
//Output Variables:
//You will store the result of your analysis and calculations in these variables
float tax_rate = 0; //Variable tax_rate will hold the tax_rate percentage. You will assign a value for tax_rate based on the Taxable Income (Table 1) table given in the studio project document.
//The value of tax ranges between 0 to 1 (E.g. for Alberta, income of equal or less than $40000 tax = 0.25)
float net_income = 0; //Net income is calculated based on tax_rate. It is the take-home income after taxes are deducted.
//i.e. net_income = gross_income * (1 - tax_rate);
float tax_amount = 0; //tax amount is the amount of taxes paid based on gross income depending on the province.
//i.e. tax_amount = gross_income * tax_rate;
// prompt for and read the province id
prov_id = JOptionPane.showInputDialog("Please enter your province's two-letter abbreviation (e.g., AB for Alberta): ");
// prompt for and read the gross income
String answer = JOptionPane.showInputDialog("Please enter your taxable income: ");
//convert user input to folat
gross_income = Float.parseFloat(answer);
net_income=gross_income*(1-tax_rate);
tax_amount=gross_income*tax_rate;
rectMode(CENTER);
// Alberta
if ( prov_id.equals("AB") || prov_id.equals("ab"))
{
if (gross_income>=0&&gross_income<=40000)
{
tax_rate=0.25;
JOptionPane.showMessageDialog(frame,"Province: "+ prov_id + "\nGross Income: "+ gross_income + "\nTax Rate: "+ tax_rate+ "\nTax Amount: "+ tax_amount+"\nNet Income: "+ net_income);
}
}
The expected out put is supposed to be this: https://imgur.com/a/Gx2XOql
So far my code displays this: https://imgur.com/a/Gx2XOql
The window where the bar graphs are shown is Processing's not one from JOptionPane.showMessageDialog() since the window is named "TaxCalculator_kEY", which i assume is the name of the file, not "Message".
This is a loan calculator program. I'm having trouble with the math. Everything else seems to be correct except for the value of the beginning balance after 2 months. Notice that the beginning balance of the 3rd month is different from the ending balance of the 2nd month. Same thing for the succeeding months. I've been trying to fix it but everything didn't work out. I need them to be the same so the ending balance of the last month will be 0.
This is a sample output of the program:
Personal Loan Payment Calculator
Enter a loan amount: 1000
Enter the loan term (months): 6
Enter the interest rate (% per year): 9
Loan Payment and Amortization Table
Months Beginning Monthly Principal Interest Ending
Balance Payment Paid Paid Balance
1 1000.00 171.07 163.57 7.50 836.43
2 836.43 171.07 164.80 6.27 671.64
3 670.41 171.07 166.04 5.03 504.37
4 501.88 171.07 167.30 3.76 334.57
5 330.78 171.07 168.59 2.48 162.19
6 157.06 171.07 169.89 1.18 -12.83
Summary:
========
Loan Amount: $1,000.00
Monthly Payment: $171.07
Number of Payments: 6
Total Interest Paid: $24.00
Annual Interest Rate: 9.00%
This is the program:
public class LoanCalculator {
public static void main(String[] args) {
System.out.println("Personal Loan Payment Calculator"); // print the name of the program
System.out.println("================================");
Scanner keyboard = new Scanner (System.in); // define a Scanner object attached to a keyboard
String badInput; // assign non-integer or non-double inputs to badInput
System.out.print("Enter a loan amount: "); // prompt the user to enter loan amount
while ( ! keyboard.hasNextDouble()) // is the first input value a double?
{
badInput = keyboard.next();
System.out.println("Error: expected a Double, encountered: " + badInput);
System.out.println("Please enter a loan amount in Double: ");
}
double loanAmount = keyboard.nextDouble(); // assign the first input to loanAmount
System.out.print("Enter the loan term (months): "); // prompt the user to enter number of months
while ( ! keyboard.hasNextInt()) // is the second input value an int?
{
badInput = keyboard.next();
System.out.println("Error: expected an Integer, encountered: " + badInput);
System.out.println("Please enter a loan term in Integer: ");
}
int loanTerm = keyboard.nextInt(); // assign the second input to loanTerm
System.out.print("Enter the interest rate (% per year): "); // prompt the user to enter the interest rate
while ( ! keyboard.hasNextDouble()) // is the first input value a double?
{
badInput = keyboard.next();
System.out.println("Error: expected an integer, encountered: " + badInput);
System.out.println("Please enter a loan amount in Double: ");
}
double interestRate = keyboard.nextDouble(); // assign the third input to interestRate
System.out.println(); // skip a line
System.out.println(" Loan Payment and Amortization Table");
System.out.printf("%s", "=============================================================");
System.out.println();
System.out.printf("%5s %10s %10s %10s %10s %10s", "Months" ,"Beginning", "Monhtly", "Principal", "Interest", "Ending");
System.out.println();
System.out.printf(" %5s %10s %10s %10s %10s %10s", "#","Balance", "Payment", "Paid", "Paid", "Balance");
System.out.println();
System.out.printf("%s ", "=============================================================");
System.out.println();
double monthlyRate = (interestRate / 100.0) / 12.0;
double monthlyPayment = (monthlyRate * loanAmount) / ( 1 - (Math.pow( 1 + monthlyRate, - loanTerm)));
double beginningBalance = loanAmount;
double interestPaid = beginningBalance * monthlyRate;
double principalPaid = monthlyPayment - interestPaid;
int total_interest_paid = 0;
for (int monthCount = 0 ; monthCount < loanTerm ; ++monthCount)
{
int months = 1 + monthCount;
beginningBalance = loanAmount - principalPaid * monthCount;
interestPaid = beginningBalance * monthlyRate;
principalPaid = monthlyPayment - interestPaid;
double endingBalance = beginningBalance - principalPaid;
System.out.printf(" %5d %10.2f %10.2f %10.2f %10.2f %10.2f\n", months, beginningBalance, monthlyPayment, principalPaid, interestPaid, endingBalance);
total_interest_paid += interestPaid;
}
System.out.printf("%s ", "=============================================================");
System.out.println();
NumberFormat currency = NumberFormat.getCurrencyInstance();
DecimalFormat percentFormat = new DecimalFormat ("0.00");
System.out.println("\nSummary:");
System.out.println("========");
System.out.println("Loan Amount: " + currency.format(loanAmount));
System.out.println("Monthly Payment: " + currency.format(monthlyPayment));
System.out.println("Number of Payments: " + loanTerm);
System.out.println("Total Interest Paid: " + currency.format(total_interest_paid));
System.out.println("Annual Interest Rate: " + percentFormat.format(interestRate) + "%");
}
}
The error is very simple:
beginningBalance = loanAmount - principalPaid * monthCount;
Remember that "principalPaid" increases every month. The total principal paid is not the last principalPaid * mouthCount but the sum of the principal paid in all months.
You could create a running total for principalPaid like you did for interest paid.
But it would be much easier to do beginningBalance = previous month endingBalance.
I am trying to accept user input for two people's hourly wage and the amount of hours of overtime they work per year.
using an algorithm I have researched, the program will tell both people the amount of money they make per year and the amount of taxes they pay, which is based on the amount that they make.
This is all fine and dandy. However, what I am now trying to do is to add a line at the end of the program which states who is paying more taxes. This would be accomplished with the method whoPaysMoreTaxes, but I have no idea what to include in that method. I know I would need a simple if/ else if/ else statement to get the job done, but I do not know how I would go about storing the taxes of person 1 and the taxes of person 2 and compare them. The output should be as follows I believe. The numbers 22, 100, 58, and 260 are user input:
Person 1's hourly wage: 22
Person 1's overtime hours for the year: 100
You will make $45540 this year
And you will pay $9108 in taxes
Person 2's hourly wage: 58
Person 2's overtime hours for the year: 260
You will make $133980 this year
And you will pay $40194 in taxes.
Person 2 is paying more taxes.
The issue I am having is finding a way to produce that final line that says who is paying more taxes.
public class conditionalsAndReturn
{
public static void main(String[] args)
{
Scanner console = new Scanner(System.in);
taxes(console, 1);
taxes(console, 2);
}
public static void taxes(Scanner console, int personNum)
{
System.out.print("Person " + personNum + "'s hourly wage: ");
int wage = console.nextInt();
System.out.print("Person " + personNum + "'s overtime hours for the year: ");
double totalOvertimeHours = console.nextInt();
int salary = annualSalary(wage, totalOvertimeHours);
System.out.println("You will make $" + salary + " this year");
System.out.println("And you will pay $" + taxation(salary) + " in taxes");
System.out.println();
}
public static int annualSalary(int wage, double totalOvertimeHours)
{
double workHoursPerWeek = 40 + totalOvertimeHours / 48;
return (int)(weeklyPay(wage, workHoursPerWeek) * 48);
}
public static double weeklyPay(int wage, double workHoursPerWeek)
{
if (workHoursPerWeek > 40)
{
return (wage * 40) + ((wage + wage / 2.0) * (workHoursPerWeek - 40));
}
else
{
return wage * workHoursPerWeek;
}
}
public static int taxation(int salary)
{
if (salary < 20000)
{
return 0;
}
else if (salary > 100000)
{
return salary * 3 / 10;
}
else
{
return salary * 2 / 10;
}
}
public static String whoPaysMoreTaxes(
}
The OOP conform coding would be, to have a class person (or better employee), with the fields: personNum, one or more of the three wage/salary variables, taxation. Add name and such if needed.
Now you can use instances of those class to store the accumulated data, and compare the objects with a compareTo.
If you were to follow true Object Oriented programming principles, then you might create a separate class which represents a Person object (or consider a nested class). Then each Person instance could have the attributes:
hourly_wage
overtime_hours
income
taxes_owed
You would then want to create as many People classes as you need, using the class instances to store data. You could then modify your method header to be:
public Person who_payes_more_taxes(Person p1, Person p2): { ... }
Inside the method you would need to decide how to compare taxes, but most likely it will look something like:
if (p1.taxes_owed > p2.taxes_owed) { return p1 }
You're definitely on the right track. I would use more variables to simplify comparing the taxes:
import java.util.Scanner;
public class ConditionalsAndReturn
{
public static void main(String[] args)
{
int personOneWage;
int personOneOvertime;
double personOnePayBeforeTax;
double personOneTaxes;
double personOneNetIncome;
int personTwoWage;
int personTwoOvertime;
double personTwoPayBeforeTax;
double personTwoTaxes;
double personTwoNetIncome;
Scanner scan = new Scanner(System.in);
System.out.print("Person 1's hourly wage: ");
personOneWage = scan.nextInt();
System.out.print("Person 1's overtime hours for the year: ");
personOneOvertime = scan.nextInt();
personOnePayBeforeTax = (40 * personOneWage) + (personOneOvertime * personOneWage * 1.5);
personOneTaxes = taxes(personOnePayBeforeTax);
personOneNetIncome = personOnePayBeforeTax - personOneTaxes;
System.out.println("You will make $" + personOneNetIncome + " this year");
System.out.println("And you will pay $" + personOneTaxes + " in taxes");
System.out.print("Person 2's hourly wage: ");
personTwoWage = scan.nextInt();
System.out.print("Person 2's overtime hours for the year: ");
personTwoOvertime = scan.nextInt();
personTwoPayBeforeTax = (40 * personTwoWage) + (personTwoOvertime * personTwoWage * 1.5);
personTwoTaxes = taxes(personTwoPayBeforeTax);
personTwoNetIncome = personTwoPayBeforeTax - personTwoTaxes;
System.out.println("You will make $" + personTwoNetIncome + " this year");
System.out.println("And you will pay $" + personTwoTaxes + " in taxes");
if (personOneTaxes > personTwoTaxes)
{
System.out.println("Person 1 is paying more in taxes.");
}
else
{
System.out.println("Person 2 is paying more in taxes.");
}
scan.close();
}
private static double taxes(double payBeforeTax)
{
if (payBeforeTax < 20000)
{
return 0;
}
else if (payBeforeTax > 100000)
{
return payBeforeTax * 3 / 10;
}
else
{
return payBeforeTax * 2 / 10;
}
}
}
I'm a junior in high school. Having a tough time figuring out how to use money format. I'm doing an exercise in A Guide to Programming in Java (Second Edition) where I have to prompt the employees for the number of burgers, fries, and sodas.
Fries are $1.09, burgers are $1.69, and sodas are $0.99.
Here is my code:
import java.util.Scanner;
/**
* Order pg. 101
*
* Garret Mantz
* 2/10/2016
*/
public class Order {
public static void main(String[]args) {
final double pburgers=1.69;
final double pfries=1.09;
final double psodas=0.99;
final double ptax=0.065;
double burgers;
double fries;
double sodas;
double totaltax;
double total;
double tax;
double tendered;
double change;
Scanner input = new Scanner(System.in);
System.out.print("Enter the amount of burgers: ");
burgers = input.nextDouble();
System.out.print("Enter the amount of fries: ");
fries = input.nextDouble();
System.out.print("Enter the amount of sodas: ");
sodas = input.nextDouble();
System.out.print("Enter the amount tendered: ");
tendered = input.nextDouble();
totaltax = (burgers*pburgers)+(fries*pfries)+(sodas*psodas);
tax = totaltax*ptax;
total = totaltax + tax;
change = tendered - total;
System.out.println("Your total before tax is: \n" + totaltax);
System.out.println("Tax: \n" + tax);
System.out.println("Your final total is: \n" + total);
System.out.println("Your change is: \n" + change);
}
}
I just want to use the money format, but I'm not sure how. I'm sure it's a dumb question, but thank you for helping out!
Change your println to these, and see if that helps:
System.out.format("Your total before tax is: $%-5.2f\n", totaltax);
System.out.format("Tax: $%-5.2f\n", tax);
System.out.format("Your final total is: $%-5.2f\n", total);
System.out.format("Your change is: $%-5.2f\n", change);
There is also this:
NumberFormat formatter = NumberFormat.getCurrencyInstance();
String totalTaxString = formatter.format(totaltax);
String taxString = formatter.format(tax);
String totalString = formatter.format(total);
String changeString = formatter.format(change);
System.out.format("Your total before tax is: %s\n", totalTaxString);
System.out.format("Tax: %s\n", taxString);
System.out.format("Your final total is: %s\n", totalString);
System.out.format("Your change is: %s\n", changeString);
Output:
Your total before tax is: $8.53
Tax: $0.55
Your final total is: $9.08
Your change is: $10.92