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.
Related
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 am working on a program that prints out the wages earned by workers including overtime pay. I am almost finished with the program. However, I am stuck on how to make a condition to fix the decimals in the wages to only the tenths and hundredths places (.00).
The condition I want is, if the number of hours worked is greater than 40 and the overtime wages have numbers in the thousandths place or more (overTimeWages has .000 or more .0000000000....), then System.out.println("$" + (Math.floor(overTimeWages * 100) / 100)); to round overTimeWages to the nearest hundredths down. I only want the tenths and hundredths place values. Else if hours worked is greater than 40 and the overtime wages have numbers only in the tenths and hundredths place, then System.out.println("$" + overTimeWages + 0);.
How do I make that condition above?
I tried overTimeWages % 0.1 != 0; but it did not work.
Below in the code comments are the values that are supposed to be inputted.
Code
import java.util.Scanner;
int payRateInCents, payRateInDollars,
hoursWorked,
overTimeHours, grossPayWithInt;
double grossPay, payRCents, payRDollars, overTimeRate;
grossPay = (double) ((payRDollars * hoursWorked));
grossPayWithInt = (payRateInCents * 40);
double grossPayWithOverTime = (double) ((grossPayWithInt) + (overTimeRate * overTimeHours));
double overTimeWages = (double) (grossPayWithOverTime / 100);
/**
2000 45 = (2000 * 40) + ((2000 * 1.5) * (45 - 40)) == 95000
2000 45 = (grossPayWithOverTime) + ((overTimeRate) * (overTimeHours)) == 95000
Then divide by 100.
2000 40 should get: $800.00
1640 41 should get: $680.60
3111 43 should get: $1384.39
1005 1 should get: $10.05
**/
if(hoursWorked > 40) {
if(overTimeWages % 0.1 != 0) {
System.out.println("$" + (Math.floor(overTimeWages * 100) / 100));
} else {
System.out.println("$" + overTimeWages + 0);
}
}
else {
if(hoursWorked < 10) {
System.out.println("$" + grossPay);
} else {
System.out.println("$" + grossPay + 0);//40 or lower
}
}
Dont use fractions or float for any variables that will hold money. Operations on float will give you unexpected result due to how floats are stored. You think 1.2 is 1.2 but it might be actually 1.19999999. That's how floats work.
I would suggest to not get into any fractions when dealing with money. Instead of 1.30$ use 130 cents.
For displaying purposes converting it is trivial:
private static DecimalFormat df = new DecimalFormat("#.##");
Syste.out.println(df.format(yourDouble));
To see how many decimals number has.
String[] split = yourDouble.toString().split("\\.");
split[0].length();
split[1].length();
So the question my teacher wrote on the white board is: Input product Name, Quantity, price. Compute the total amount. If total amount is greater than 2000 discount is 5%, if total amount is greater than 5000 discount is 10%, if greater than 10000 discount is 20%
I know that you have to do this kind of format.
if (cost > 2000)
discount = 0.05;
I would put in the correct things before than like
String prodName;
int qty, price;
double cost;
double discount;
I know what I put there is wrong but I think that's how the format of it goes before doing the nested if statement. I really need help on this. I don't need to be given the answers for this because that's spoon-feeding to the max level. I just need some pointers and a guide in order to find out what to do.
First of all you need to read your book thoroughly. Obviously this can be a good start. First learn how if-then works, next if-then-else and finally if-then-else if-then-else. Now lets analyze your question:
Input product Name, Quantity, price. Compute the total amount. If total amount is greater than 2000 discount is 5%, if total amount is greater than 5000 discount is 10%, if greater than 10000 discount is 20%.
Clearly you are going to set one variable, lets call it discount, with checking some condition. For explanation, say if the total amount is greater than 10000, then you are going to set discount = 20%. But careful, when total amount is greater than 10000, it also leads total amount is greater than 5000 or 2000 too! Then are you going to set discount = 10% or discount = 5% respectively? No, you are not.
Hence, to solve your problem, if a higher prioritize condition is already matched, you are not going to check any other conditions. So we will do the following:
discount;
total_amount = some Cost you calculated/inputted
if(total_amount > 10000) {
discount = 0.2;
} else if(total_amount > 5000) {
discount = 0.05;
} else if(total_amount > 2000) {
discount = 0.01;
} else {
discount = 0.00; // no discount for you coz total_amount less than or equal to 2000
}
Now what happens here? If the first test expression is true (total_amount > 10000), it executes the code inside the braces { } just below it and no other block is executed. But if the first test expression is false, it checks the second test expression (total_amount > 5000). If the second test expression is true, it executes the statement/s inside the braces { } just below it and no other block is executed. This process continues. If all the test expression are false, code/s inside else is executed and the control of program jumps below the if-else.
When you fully understand if-else then you can solve this problem in many different ways. Best of luck.
first declare all your variables like you did:
String prodName="";
int qty, price;
double cost; //your cost will be stored here
double discount =0;
Then do your calculations
if (cost > 2000 && cost <= 5000)
discount = 0.05;
else if(cost > 5000 && cost <= 10000){
discount = 0.1;
}else if(cost > 10000){
discount = 0.2;
}
You can do it nested and in the order that the question asks if it will be easier to understand. We just update the discount as necessary. Note that the other answers might be prettier, but this is a way to do it nested:
double cost = ...;
double discount = 0.0;
if (cost > 2000)
{
discount = 0.05;
if (cost > 5000)
{
discount = 0.10;
if (cost > 10000)
{
discount = 0.20;
}
}
}
cost = cost - (cost * discount);
You could do it backwards, or with else if and else statements too.
if (cost > 10000)
discount = 0.2;
else if (cost > 5000)
discount = 0.1;
else if (cost > 2000)
discount = 0.05;
Hope the below code can help you......
if (cost > 10000)
discount = 0.2;
else if (cost > 5000)
discount = 0.1;
else if (cost > 2000)
discount = 0.05;
else
System.out.println("cost is less than 2000 hence no discount applied");
if (cost > 10000)
discount = 0.2;
else if(cost > 5000){
discount = 0.1;
}else if(cost > 2000){
discount = 0.05;
} else {
discount = 0;
}
double total = cost - (cost * discount);
When using if and else ifs if the first if statement is true then that code is executed and none of the other else ifs are checked. If the first if is false then each else if following the if are checked in the order they appear. If one of them is true then that code is executed and none of the others are checked. However, if none are true and you had an else block that code would get executed.
I don't think nested if statements are necessary in this case. Instead you can reverse the order of the if statements so that it first checks for cost > 10000, then cost > 5000, and finally cost > 2000.
Also, if the net amount you mentioned is the cost after discount, then you can do a simple calculation after the if statements. It would look something like this:
double discount = 0;
if (cost > 10000){
discount = 0.2;
}
else if(cost > 5000){
//similar to above, won't spoon-feed this
}
else if(cost > 2000){
//similar to above, won't spoon-feed this
}
double netAmount = cost * (1 - discount);
I know you asked for nested if statements, but you could seriously shorten the solution to this problem using a ternary operator, especially since this is primarily used for assigning a value to discount. Probably considerably more complex than what you were looking for but this could work:
double cost, netAmount;
//get cost
double discount = cost > 10000 ? 0.2 : cost > 5000 ? 0.1 : cost > 2000 ? 0.05 : 0;
netAmount = discount * cost;
Brief Explanation
This works just like nested if statements, but it's a neater, if less readable, way of writing them. Each boolean expression, such as
cost > 10000
is evaluated to either or true or false, as per all boolean expressions. The values after the ternary operator, the ?, are assigned if the expression returns true. Values after the : are assigned if the expression returns false. In this case if cost is greater than 10000, the value 0.2 is assigned. If cost is less than 10000, we want to evaluate another boolean expression so we nest another boolean expression like so:
cost > 10000 ? 0.2 : cost < 5000...
The final : indicates what value will be assigned should all other expression evaluate to false, just like a terminating else statement in an if - else block.
Just a few pointers, you are to compare the price, if you do it in reverse order you could do :
if (cost > 10000)
discount = 0.2;
else if (cost > 5000)
discount = 0.1;
else if (cost > 2000)
discount = 0.05;
This is handy because you aren't nesting if statements and it still is correct.
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.