How to iterate a variable in Java - java

So Im sort of stumped on how to do the following.
I have my program outputting the correct variables in a table like format that I want. However, I dont quite understand how to make one of the variables increase in value as well.
Below is the code.
package annualsalarywithcommisions;
/**
*
* #author TDavis
*/
public class Calculations {
public double baseSalary = 55000;
public double localTotalSalary;
public double salesTarget = 165000;
public double potentialSalary;
public void PayCalculator() {
//Method for calculating the total wages paid to a sales rep.
double localSales = ComissionsWk3.Sales;
if (localSales < (.75 * salesTarget)) {
localTotalSalary = baseSalary;
//When sales are less than 75% of sales target, they only make
//the salary.
} else if ((localSales > (.75 * salesTarget)) && (localSales <= salesTarget)) {
localTotalSalary = (.14 * localSales) + baseSalary;
//Total salary is calculated with the 14% commission rate when
//75% of the salesTarget has been met.
} else if (localSales < salesTarget) {
localTotalSalary = (.216 * localSales) + baseSalary;
//Total salary is calculated with the acceleration factor and the
//base salary included when total sales exceeds the sales target.
}
}
public double getCalculatedSalary() {
return localTotalSalary; //method for returnin te' calculated salary total.
}
public double CompensationTable() {
double localSales = ComissionsWk3.Sales;
for (double counter = localSales; counter < localSales * 1.5;
counter += 5000) {
if (counter < (.75 * salesTarget)) {
potentialSalary = baseSalary;
//When sales are less than 75% of sales target, they only make
//the salary.
} else if ((localSales > (.75 * salesTarget)) && (localSales <= salesTarget)) {
potentialSalary = (.14 * localSales) + baseSalary;
//Total salary is calculated with the 14% commission rate when
//75% of the salesTarget has been met.
} else if (localSales < salesTarget) {
potentialSalary = (.216 * localSales) + baseSalary;
//Total salary is calculated with the acceleration factor and the
//base salary included when total sales exceeds the sales target.
}
System.out.println("Total Sales: " + counter + "\tTotal " + "Compensation: " + potentialSalary);
}
return 0;
}
}
What I'm stumped on is how to make the output potentialSalary come back with the calculated potentialSalary.
Essentially whenever the 5k increase happens, get the 14% or 21.6% increase added into that variables total each time it runs through the loop and set it as such.
Any ideas are very much welcomed.
I have actually figured it out - but apparently cant answer my own question. Below is the fixed code.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package annualsalarywithcommisions;
/**
*
* #author TDavis
*/
public class Calculations {
public double baseSalary = 55000;
public double localTotalSalary;
public double salesTarget = 165000;
public double potentialSalary;
public void PayCalculator() {
//Method for calculating the total wages paid to a sales rep.
double localSales = ComissionsWk3.Sales;
if (localSales < (.75 * salesTarget)) {
localTotalSalary = baseSalary;
//When sales are less than 75% of sales target, they only make
//the salary.
} else if ((localSales > (.75 * salesTarget)) && (localSales <= salesTarget)) {
localTotalSalary = (.14 * localSales) + baseSalary;
//Total salary is calculated with the 14% commission rate when
//75% of the salesTarget has been met.
} else if (localSales < salesTarget) {
localTotalSalary = (.216 * localSales) + baseSalary;
//Total salary is calculated with the acceleration factor and the
//base salary included when total sales exceeds the sales target.
}
}
public double getCalculatedSalary() {
return localTotalSalary; //method for returnin te' calculated salary total.
}
public double CompensationTable() {
double localSales = ComissionsWk3.Sales;
for (double counter = localSales; counter < localSales * 1.5;
counter += 5000)
{
if (counter < (.75 * salesTarget)) {
potentialSalary = baseSalary;
//When sales are less than 75% of sales target, they only make
//the salary.
} else if ((counter > (.75 * salesTarget)) && (counter <= salesTarget)) {
potentialSalary = (.14 * counter) + baseSalary;
//Total salary is calculated with the 14% commission rate when
//75% of the salesTarget has been met.
} else if (counter < salesTarget) {
potentialSalary = (.216 * counter) + baseSalary;
//Total salary is calculated with the acceleration factor and the
//base salary included when total sales exceeds the sales target.
}
System.out.println("Total Sales: " + counter + "\tTotal " + "Compensation: " + potentialSalary);
}
return 0;
}
}

The third case in your if/else will never be entered because of the previous case's <=. There's not really an upper bound on potential salary so it's hard to answer, but they have the potential to make base + 21.6% it looks like. So I'd make a function that took the sales and then provided the base + 21.6% of that. The CompensationTable() and PayCalculator() functions are confusing (should not be capitalized either). It looks like you were trying to make CompensationCalculator() into your potential function, but returned 0 instead of a value.

Related

avoiding code redundancies for a calculation in Java

I have a calculation where i can sum or subtract something but this depends on a simple condition. My problem is, that I don't know how I can change the code, so i don't need to write the calculation twice just with the difference of the + or -. Hopefully somebody can helf me. Thanks in advance.
public void changePrice(Stock stock, int amount, boolean isBuying) {
double roundRandomNumber = Math.round((0.5 + Math.random()) * 100) / 100.00;
double newPrice;
//calculates plus or minus depending on the buyoption
if (isBuying) {
newPrice = Math.round((stock.getPrice() + roundRandomNumber * 0.1 * amount) * 100) / 100.00;
} else {
newPrice = Math.round((stock.getPrice() - roundRandomNumber * 0.1 * amount) * 100) / 100.00;
}
if (newPrice > 0 && newPrice < 3000) {
stock.setPrice(newPrice);
}
}
You can use a +1 or -1 coefficient based on isBuying value.
newPrice = Math.round((stock.getPrice() + (isBuying ? 1.0 : -1.0) * roundRandomNumber * 0.1 * amount) * 100) / 100.00;
You could try by extracting just the factor in the condition:
public void changePrice(Stock stock, int amount, boolean isBuying) {
double roundRandomNumber = Math.round((0.5 + Math.random()) * 100) / 100.00;
double newPrice;
//calculates plus or minus depending on the buyoption
double factor;
if (isBuying) {
factor = 1.0
} else {
factor = -1.0
}
newPrice = Math.round((stock.getPrice() + (factor * roundRandomNumber) * 0.1 * amount) * 100) / 100.00;
if (newPrice > 0 && newPrice < 3000) {
stock.setPrice(newPrice);
}
}
I come up with substitution of roundRandomNumber yielding an expression with ( / 100) * 0.1 which can simplified to * 0.001.
Also round(0.5 + x) can be ceil(x).
Or use 1 + new Random().nextInt(100).
double roundRandomNumber = Math.ceil((Math.random()) * 100) * 0.001 * amount;
double newPrice = stock.getPrice();
if (isBuying) {
newPrice += roundRandomNumber;
} else {
newPrice -= roundRandomNumber;
}
newPrice = Math.round((newPrice * 100) / 100.00;
if (newPrice > 0 && newPrice < 3000) {
stock.setPrice(newPrice);
}
For the rest it is the reserved register principle: I do stepwise things to newPrice.
The boundary condition excludes 0, which is questionable.
Of course BigDecimal should be mentioned. The complexity basically stems from wanting fixed point arithmetic with floating point. Unless you need speed, BigDecimal code can be more readable, though verbose.

i have this assignment on java i am not sure if i am doing this right

Foo Corporation needs a program to calculate how much to pay their hourly employees.
The US Department of Labor requires that employees get paid time and a half for any hours over 40 that they work in a single week.
For example, if an employee works 45 hours, they get 5 hours of overtime, at 1.5 times their base pay.
The State of Massachusetts requires that hourly employees be paid at least $8.00 an hour.
Foo Corp requires that an employee not work more than 60 hours in a week.
An employee gets paid (hours worked) × (base pay), for each hour up to 40 hours. For every hour over 40, they get overtime = (base pay) × 1.5. The base pay must not be less than the minimum wage ($8.00 an hour). If it is, print an error. If the number of hours is greater than 60, print an error message.
Create a new class called FooCorporation.
Write a method that takes the base pay and hours worked as parameters, and prints the total pay or an error. Write a main method that calls this method for each of these employees:
Base Pay Hours Worked Employee 1 $7.50 35 Employee 2 $8.20 47 Employee 3 $10.00 73
You have to read base pay and hours from a text file in this format.
Employee, basePay, hours
1, 8, 40,
2, 9, 33,
3, 10, 70
Here is my code:
package foocorporation;
public class FooCorporation {
double minimumWage = 8.0;
int maxHours = 60;
float x;
int y;
public static void main(String[] args) {
salaryCalculation(x,y, minimumWage, maxHours);
salaryCalculation(x,y, minimumWage, maxHours);
salaryCalculation(x,y, minimumWage, maxHours);
}
public static void salaryCalculation
(double basePay, int hoursWorked, double minimumWage, int maxHours){
double totalSalary = 0;
if ((basePay < minimumWage) || (hoursWorked > maxHours)){
System.out.println("Error!");
}
else {
if (hoursWorked > 40){
totalSalary = basePay * 40 + 1.5*basePay*(hoursWorked - 40);
}
else {
totalSalary = basePay * hoursWorked;
}
System.out.println("Your total salary is " + totalSalary);
}
}
}
have a look at this
UPDATE
if you want to take the input from the user as you asked later
public class FooCorporation {
static final double minimumWage = 8.0; // static means that can be accessed without creating an object of the class and instantiating it
static final int maxHours = 60; // final means constant = cannot be changed after declared
static double basePay=0; // initialize them to zero, at least you know your program won't throw null pointer exception if forgot to set their
//values before invoking the method
static int hoursWorked=0;
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
for (int i=1; i<=3; i++, System.out.println()){
System.out.println("For Employee Number: " + i);
System.out.println("Enter Base Pay:");
basePay = in.nextDouble();
System.out.println("Enter Hours Worked:");
hoursWorked = in.nextInt();
salaryCalculation();
}
}
public static void salaryCalculation(){
double totalSalary = 0;
if ((basePay < minimumWage) || (hoursWorked > maxHours)){
System.out.println("Error!");
}
else {
if (hoursWorked > 40){
totalSalary = basePay * 40 + 1.5*basePay*(hoursWorked - 40);
}
else {
totalSalary = basePay * hoursWorked;
}
System.out.println("Your total salary is " + totalSalary);
}
}
}
result will be for your inputs for example:
For Employee Number: 1
Enter Base Pay:
7.5
Enter Hours Worked:
35
Error!
For Employee Number: 2
Enter Base Pay:
8.2
Enter Hours Worked:
47
Your total salary is 414.1
For Employee Number: 3
Enter Base Pay:
10
Enter Hours Worked:
37
Your total salary is 370.0
package foocorporation;
public class Foocorporation {
final static double minimumWage = 8.0;
final static int maxHours = 60;
public static void main(String[] args) {
float x;
int y;
x=7.5f;
y=35;
salaryCalculation(x,y);
x=8.2f;
y=47;
salaryCalculation(x,y);
x=10.0f;
y=73;
salaryCalculation(x,y);
}
public static void salaryCalculation(double basePay, int hoursWorked){
double totalSalary = 0;
if ((basePay < minimumWage) || (hoursWorked > maxHours)){
System.out.println("Error!");
}
else {
if (hoursWorked > 40){
totalSalary = basePay * 40 + 1.5*basePay*(hoursWorked - 40);
}
else {
totalSalary = basePay * hoursWorked;
}
System.out.println("Your total salary is " + totalSalary);
}
}
}

I need help understanding the programming challenge called Shipping Charges

The question says The Fast Freight Shipping Company charges the following rates:
Weight of Package Rate per 500 Miles Shipped
2 pounds or less $1.10
Over 2 pounds but not more than 6 pounds $2.20
Over 6 pounds but not more than 10 pounds $3.70
Over 10 pounds $3.80
The shipping charge per 500 miles are not prorated. For example, if a 2-pound package is shipped 550 miles, the charges would be $2.20. Write a program that asks the user to enter the weight of a package and then displays the shipping charges.
My problem is that I keep receiving two different answers everytime I put in a weight and distance. For example when I enter the weight as 2 pounds and the distance as 500 miles I get the answers $0.0 and $3.8 which are both incorrect answers. It looks like some weights that I enter are correct answers and others I enter give me incorrect answers. Heres my program:
//import java utilities for scanner class
import java.util.Scanner;
public class ShippingCharge
{
public static void main (String[] args)
{
//Declare and initialize variable to hold the entered weight.
int weight = 0;
//Declare and initialize variable to hold the entered distance.
double distance = 0.0;
//This variable will hold the calculated rate.
double rate;
//This will decide if the shipping charge will advance up one level.
int distanceMultiplier = (int)distance / 500;
//This will hold the increments of the shipping charge.
int distanceRemainder;
//Create a Scanner object for the input.
Scanner input = new Scanner(System.in);
//Get the weight of the package.
System.out.println("What is the weight of the package (in pounds)?");
weight = input.nextInt();
//Get the shipping distance of the package.
System.out.println("What is the shipping distance (in miles)?");
distance = input.nextDouble();
distanceRemainder = (int)distance % 500;
if (distanceRemainder == 0)
{
if (weight <= 2)
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 1.10));
}
else if (weight > 2 && weight <= 6)
{
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 2.20));
}
else if (weight > 6 && weight <= 10)
{
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 3.70));
}
else
{
System.out.println("Total Shipping Cost is: $" + (distanceMultiplier * 3.80));
}
if (distanceRemainder != 0)
{
if (weight <= 2)
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 1.10);
}
else if (weight > 2 && weight <= 6)
{
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 2.20);
}
else if (weight > 6 && weight <= 10)
{
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 3.70);
}
else
{
System.out.println("Total Shipping Cost is: $" +(distanceMultiplier + 1) * 3.80);
}
//end program
System.exit(0);
}//end main
}//end class
This will work for you
public static void main(String[] args) {
int weight = 0;
double distance = 0.0 , distanceExtra ;
Scanner in = new Scanner(System.in);
System.out.println("Weight ? ");
weight = in.nextInt();
System.out.println("Distance ? ");
distance = in.nextDouble();
distanceExtra = distance / 500;
distanceExtra = Math.ceil(distanceExtra);
if (weight <= 2) {
System.out.printf("charge is :" , (distanceExtra * 1.10));
}
else if (weight > 2 && weight <= 6)
{
System.out.printf("charge is :" , (distanceExtra * 2.20));
}
else if (weight > 6 && weight <= 10)
{
System.out.printf("charge is :" , (distanceExtra * 3.70));
}
else if (weight > 10)
{
System.out.printf("charge is :" , (distanceExtra * 4.80));
}
}
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// write your code here
int weight = 0;
double distance = 0.0 ;
Scanner keyboard =new Scanner(System.in);
System.out.println("Enter the Distance");
distance = keyboard.nextDouble();
System.out.println("Enter the Weight");
weight = keyboard.nextInt();
if (weight <= 2) {
System.out.println("charge is : " + "$"+1.10);
}
else if (weight > 2 && weight <= 6)
{
System.out.println("charge is : " + "$"+2.20);
}
else if (weight > 6 && weight <= 10)
{
System.out.println("charge is : " + "$"+3.70);
}
else if (weight > 10)
{
System.out.println("charge is :" + "$"+4.80);
}
}
}

How to round to the nearest cent in Java

So I am writing a program that does some financial calculations. However, because I used double for my data types, the cents are not rounded. Here is the source code:
public class CentRoundingTest {
public static void main(String[] args) {
System.out.println("TextLab03, Student Version\n");
double principle = 259000;
double annualRate = 5.75;
double numYears = 30;
// Calculates the number of total months in the 30 years which is the
// number of monthly payments.
double numMonths = numYears * 12;
// Calculates the monthly interest based on the annual interest.
double monthlyInterest = 5.75 / 100 / 12;
// Calculates the monthly payment.
double monthlyPayment = (((monthlyInterest * Math.pow(
(1 + monthlyInterest), numMonths)) / (Math.pow(
(1 + monthlyInterest), numMonths) - 1)))
* principle;
// calculates the total amount paid with interest for the 30 year time.
// period.
double totalPayment = monthlyPayment * numMonths;
// Calculates the total interest that will accrue on the principle in 30
// years.
double totalInterest = monthlyPayment * numMonths - principle;
System.out.println("Principle: $" + principle);
System.out.println("Annual Rate: " + annualRate + "%");
System.out.println("Number of years: " + numYears);
System.out.println("Monthly Payment: $" + monthlyPayment);
System.out.println("Total Payments: $" + totalPayment);
System.out.println("Total Interest: $" + totalInterest);
}
}
My instructor also does not want this to use the DecimalFormat class. I was thinking to obtain the cents value by doing: variable-Math.floor(variable), and then rounding that amount to the nearest hundredth, then adding that together.
Without using the JDK-provided library classes that exist for this purpose (and would normally be used), the pseudocode for rounding arithmetically is:
multiply by 100, giving you cents
add (or subtract if the number is negative) 0.5, so the next step rounds to the nearest cent
cast to int, which truncates the decimal part
divide by 100d, giving you dollars)
Now go write some code.
Well, if you cannot use the DecimalFormat class, you could use printf():
TextLab03, Student Version
Principle : $259,000.00
Annual Rate : 5.75%
Number of years : 30.00
Monthly Payment : $1,511.45
Total Payments : $544,123.33
Total Interest : $285,123.33
public class CentRoundingTest {
public static void main(String[] args) {
System.out.println("TextLab03, Student Version\n");
double principle = 259000;
double annualRate = 5.75;
double numYears = 30;
// Calculates the number of total months in the 30 years which is the
// number of monthly payments.
double numMonths = numYears * 12;
// Calculates the monthly interest based on the annual interest.
double monthlyInterest = 5.75 / 100 / 12;
// Calculates the monthly payment.
double monthlyPayment = (((monthlyInterest * Math.pow(
(1 + monthlyInterest), numMonths)) / (Math.pow(
(1 + monthlyInterest), numMonths) - 1)))
* principle;
// calculates the total amount paid with interest for the 30 year time.
// period.
double totalPayment = monthlyPayment * numMonths;
// Calculates the total interest that will accrue on the principle in 30
// years.
double totalInterest = monthlyPayment * numMonths - principle;
printAmount("Principle", principle);
printPercent("Annual Rate", annualRate);
printCount("Number of years", numYears);
printAmount("Monthly Payment", monthlyPayment);
printAmount("Total Payments", totalPayment);
printAmount("Total Interest", totalInterest);
}
public static void printPercent(String label, double percentage) {
//System.out.printf("%-16s: %,.2f%%%n", label, percentage);
printNumber(label, percentage, "", "%", 16);
}
public static void printCount(String label, double count) {
//System.out.printf("%-16s: %,.2f%n", label, count);
printNumber(label, count, "", "", 16);
}
public static void printAmount(String label, double amount) {
//System.out.printf("%-16s: $%,.2f%n", label, amount);
printNumber(label, amount, "$", "", 16);
}
public static void printNumber(String label, double value, String prefix, String suffix, int labelWidth) {
String format = String.format("%%-%ds: %%s%%,.2f%%s%%n", labelWidth);
System.out.printf(format, label, prefix, value, suffix);
}
}

Working out taxable income 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.

Categories

Resources