Calculate sales tax according to the price - java

I am trying to do on the java assignment and the scenario is as follows:
A sales tax of 7% is levied on all goods and services consumed. It is also mandatory that all the price tags should include the sales tax. For example, if an item has a price tag of $107, the actual price is $100 and $7 goes to the sales tax.
Write a program using a loop to continuously input the tax-inclusive price (as "double"); compute the actual price and the sales tax (in "double"); and print the results rounded to 2 decimal places. The program shall terminate in response to input of -1; and print the total price, total actual price, and total sales tax.
However, when I try to compute the sales tax, instead of showing this:
Enter·the·tax-inclusive·price·in·dollars·(or·-1·to·end): 107
Actual·Price·is: $100.00
Sales·Tax·is: $7.00
My calculation shows this:
Enter the tax-inclusive price in dollars (or -1 to end): 107
Actual price is $99.51
Sales Tax is: $7.49
I am not sure what's wrong with my coding.
import java.util.Scanner;
public class SalesTax{
public static void main(String[] args) {
// Declare constants
final double SALES_TAX_RATE = 0.07;
final int SENTINEL = -1; // Terminating value for input
// Declare variables
double price, actualPrice, salesTax; // inputs and results
double totalPrice = 0.0, totalActualPrice = 0.0, totalSalesTax = 0.0; // to accumulate
// Read the first input to "seed" the while loop
Scanner in = new Scanner(System.in);
System.out.print("Enter the tax-inclusive price in dollars (or -1 to end): ");
price = in.nextDouble();
while (price != SENTINEL) {
// Compute the tax
salesTax = SALES_TAX_RATE * price;
actualPrice = price - salesTax;
// Accumulate into the totals
totalPrice = actualPrice + salesTax;
totalActualPrice = actualPrice + actualPrice;
totalSalesTax = salesTax + salesTax;
// Print results
System.out.println("Actual price is $" + String.format("%.2f",actualPrice));
System.out.println("Sales Tax is: $" + String.format("%.2f",salesTax));
// Read the next input
System.out.print("Enter the tax-inclusive price in dollars (or -1 to end): ");
price = in.nextDouble();
// Repeat the loop body, only if the input is not the sentinel value.
// Take note that you need to repeat these two statements inside/outside the loop!
}
// print totals
System.out.println("Total price is: " + String.format("%.2f",totalPrice));
System.out.println("Total Actual Price is: " + String.format("%.2f",totalActualPrice));
System.out.println("Total sales tax is: " + String.format("%.2f",totalSalesTax));
}
}
Any help would be appreciated. Thank you!

You're wrong with these two lines:
salesTax = SALES_TAX_RATE * price;
actualPrice = price - salesTax;
You're calculating the sales on the already-saled price, try following me:
Your price is the composition of the actualPrice and the tax on actualPrice:
price = actualPrice + SALES_TAX_RATE * actualPrice
so you can mathematically do the following passages:
price = actualPrice * (1 + SALES_TAX_RATE)
actualPrice = price / (1 + SALES_TAX_RATE)
So, try changing the assigment of actualPrice, then calculate the tax on your actualPrice:
salesTax = SALES_TAX_RATE * actualPrice;

You should calculate actual price first and with the help of that calculate sales tax rate
and instead of using this
salesTax = SALES_TAX_RATE * price; actualPrice = price - salesTax;
calculate using this:
actual_price = price / 1.07; tax_price = price - actual_price;
1.07 came from dividing tax % with 100 and adding 1 to it(you can do this to any amount of %)

I came across something similar and used this logic. You need to divide the sales tax by 100 like 7/100 with 7 being the percentage of your tax variable or you can multiply by .01 then take the result of that and add it to your variable's total value. 1% is .01 of 100%. So 7% would be .07 multiplied by your variable and added to the total you are trying to calculate. If you want precision and not rounded to the nearest integer then just set parameters on the Math.round function or don't even use it at all.
public static void solve(double meal_cost, int tip_percent, int tax_percent) {
double tip = Math.round((tip_percent * .01) * meal_cost);
double tax = Math.round((tax_percent * .01) * meal_cost);
int total_cost = (int)(meal_cost + tip + tax);
System.out.println(total_cost);
}

The problem is your sales tax calculation, try:
final double SALES_TAX_RATE = 7;
salesTax = price / (100 + SALES_TAX_RATE) * SALES_TAX_RATE;

Related

How do I fix the tax rate operation?

The goal is to provide the total sale, however, the tax rate is not calculating correctly since it keeps outputting 0.0.
import java.util.Scanner; //Required for axquiring user's input
public class salesTax {
public static void main(String[] args) {
int retailPrice; //Holds the retail price
int taxRate; //Holds sales tax rate
double salesTax; //Holds sales tax
double totalSale; //Holds total sale
//Scanner object to acquire user's input
Scanner input = new Scanner(System.in);
//Acquire user's retail price
System.out.println("What is the retail price of the item being purchased? ");
retailPrice = input.nextInt();
//Acquire user's sales tax rate
System.out.println("What is the sales tax rate? ");
taxRate = input.nextInt() / 100;
//Display the sales tax for the purchase
salesTax = retailPrice * taxRate; //Calculates the sales tax
System.out.println("The sales tax for the purchase is: " + salesTax);
//Display the total of the sale
totalSale = retailPrice + salesTax; //Calculate the total sale
System.out.println("The total of the sale is: " + totalSale);
}
}
Is there a way to fix the tax rate to produce accurate calculations, given that the tax rate is inputted by the user?
taxRate = input.nextInt() / 100;
This will give you 0 because you are dividing by an integer. You can take the number in as a float and divide by 100
float taxRate;
taxRate = input.nextFloat() / 100;
To calculate the tax rate you are reading an integer from System input and you are dividing it by 100 which gives an integer result, I think you are entering values less than 100. You need to read the values from the scanner as a float.
try this instead:
float taxRate;
taxRate = input.nextFloat() / 100;
EDIT:
As mentioned in the comments the taxRate value is between 0 and 1, so you should declare the taxRate as float or double.
Your tax rate needs to be a double since you're dividing it by 100 and then assigning it taxRate. Since tax rate is an int, it will truncate the value leaving only the integer value.
If taxRate = 7 and then you divide it by 100, you get 0.07. Since taxRate is an Integer value, when Java sees said 0.07 it will get rid of the decimal and only leave the whole number. Therefore, say taxRate = 3.9999, since taxRate is an int, it will truncate the value leaving 3. To fix this, change taxRate to a double.
Also, you need to read taxRate as a double value. To read a double value using Scanner, it will be taxRate = input.nextDouble() / 100;

Error when adding parenthesis in multiplying int and double in java why?

This is a working code but I am wondering after a full research on multiplying ints and doubles in Java I still can't see why the snippet below the code would give an error. Any help please?
public class Arithmetic {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double mealCost = scan.nextDouble(); // original meal price
int tipPercent = scan.nextInt(); // tip percentage
int taxPercent = scan.nextInt(); // tax percentage
scan.close();
// Calculate Tax and Tip:
double tip = mealCost * tipPercent / 100; //HERE IS MY PROBLEM
double tax = mealCost * taxPercent / 100; //HERE IS MY PROBLEM
// cast the result of the rounding operation to an int and save it as totalCost
int totalCost = (int) Math.round(mealCost + tax + tip);
System.out.println("The total meal cost is " + totalCost + " dollars.");
}
}
Knowing that this answer is more logical and gives a different value than the one above?!
double tip = meal * (tipPercent/100);
double tax = meal * (taxPercent/100);
In your 1st example, the multiplication is performed first, resulting in a double number that is then divided by 100, giving the correct double result:
mealCost * tipPercent / 100;
In your 2nd version, an integer division is performed first, resulting in an integer result. Assuming that tipPercent less than 100, the result will be zero.
If you like the second version better, just use a floating point constant:
double tip = meal * (tipPercent/100.0);
Let's imagine:
int tipPercent = 10;
double mealCost = 100.123d;
And
double tip = mealCost * tipPercent / 100;
1. 100.123(double) * 10(int) = 1001.23(double)
2. 1001.23(double) / 100(int) = 10.0123(double)
In the second:
double tip = mealCost * (tipPercent / 100);
10(int) / 100(int) = 0(int)
100.123(double) * 0 = 0(double)

Return to start of loop java

This is a program that lets the user enter the loan amount and loan period in number of years and displays the monthly and total payments for each interest rate starting from 5% to 8%, with an increment of 1/8.
I may have over-indulged myself here as I'm pretty new to programming, but I'm in too deep and want to figure this out.
With my current code the first line outputs correctly, displaying the rate, total and monthly. However, after that the code just continues to output the inner most loop. I need to return to the start of the loop. It would greatly be appreciated if you could point me in the right direction.
P.S. I am aware that my padding isn't in place. My biggest concern is getting the algorithm down on "paper" first, and then worrying about the beauty of it.
package loancalc194;
import java.util.Scanner;
public class LoanCalc194 {
public static void main(String[] args) {
//LOAN CALCULATOR
//user enters loan AMOUNT, loan PERIOD(years),
//output displays MONTHLY and TOTAL payments
//^displayed per 1/8 increment from 5-8% interest
Scanner in = new Scanner(System.in);
//prompt user
//retrieve loan amount and period
System.out.print("Please enter the loan amount: ");
double amount = in.nextDouble();
System.out.print("Please enter the loan period (years): ");
int period = in.nextInt();
//INTEREST LOOP///////////////////////////////////////////////////
double interest = .05000;
double inc = 0.00125;
interest = interest + inc;
double monthly = 0;
double total = 0;
System.out.println("Interest Rate\t\t\tTotal Payment\tMonthly Payment");
while (interest < .08){
//interest = interest + inc;
System.out.print(interest + "\t");
while (true){
total = (amount * period) + (interest * amount);
System.out.print("\t" + total + "\t\t");
while (true) {
monthly = ((total / period) / 12);
System.out.println(monthly);
//interest = interest + inc;
}
}
}
One loop should be enough for what you want.
Your two while(true) loops do nothing else than looping on the same values forever.
In the following code, the interest gets incremented and the new calculations computed at each loop until interest reaches your max value, this is probably what you need.
double interest = .05000;
double inc = 0.00125;
double monthly = 0;
double total = 0;
while (interest < .08){
System.out.print(interest + "\t");
total = (amount * period) + (interest * amount);
System.out.print("\t" + total + "\t\t");
monthly = ((total / period) / 12);
System.out.println(monthly);
interest = interest + inc;
}

Java - calculating total with cost and unknown number of items

I have a task here: Define a class PayPerView with method moviefee() that calculates the monthly charges for movies rented. The method should take one argument representing number of movies rented and return the fee as a double.
The rental fee fee is $6.99 per movie. Preferred customers that rent more than 10 per month get a discount of 5%.
Here's my code so far:
public class PayPerView {
public static void main(String [] args){
}
public static double moviefee(int n){
double fee = 6.99;
double total= n*fee;
System.out.println("Your balance due this month is" + total);
//return 6.99*n * ((n>10) ? 0.95:1);
}}
I know it's awful, I'm sorry and you can ignore that last line of code I commented out because I'm going to redo it and turn it into an if statement. I thought maybe I should use an array, but I can't right? Because I don't know how many movies are/will be rented? Should I use an arraylist for the number of movies rented?
Actually that line you commented out looks pretty much exactly what you are trying to do anyway. Is there something particularly wrong with it?
If you really need to output the result on the console...
final double fee = 6.99;
double total = n * fee * (n > 10 ? .95 : 1.0);
System.out.println("Your balance due this month is" + total);
return total;
I don't see why you'd use an ArrayList if you don't have any data to put into it.
You'd probably want to try something along these lines:
double total = n * fee;
if (n > 10) {
total *= 0.95;
}
I also see that you wanted to use the ternary operator, so you could replace the above code block with
double total = n * fee * (n > 10 ? 0.95 : 1.0);
Your on the right track
public static double moviefee(int n){
double fee = 6.99;
double total;
if(n <= 10){
total= n*fee;
}
else{
total= n*fee - (n*fee*0.05); //5 percent discount
}
System.out.println("Your balance due this month is" + total);
return total;
}
Edit: added double total;

Math.pow difficulty

When I enter 1000 for investment amount 4.25 for monthly interest rate and 1 for years, why do I get the result 4.384414858452464E11 instead of the expected 1043.34?
import java.util.Scanner;
public class FinancialApplicationFutureInvestment_13 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter investment amount: ");
int investmentAmount = input.nextInt();
System.out.println("Enter monthly interest rate: ");
double monthlyInterestRate = input.nextDouble();
System.out.println("Enter number of years");
int numOfYears = input.nextInt();
double futureInvestmentValue = investmentAmount *
(Math.pow(1 + monthlyInterestRate, numOfYears * 12));
System.out.println("Accumulated value is: " + futureInvestmentValue);
double test = Math.pow(1 + monthlyInterestRate, numOfYears * 12);
System.out.println(test);
}
}
Monthly interest rate will probably need to be entered as 0.0425
1 + monthlyInterestRate
Is monthlyInterestRate a raw factor, or is it expressed in percentage points?
Try dividing by one hundred.
the formula is
A = P(1+r/100)^n
so it should be
investmentAmount * (Math.pow(1 + (monthlyInterestRate/100), numOfYears * 12));
well, you compute 1+4.25 (5.25) as monthly interest rate, instead of 1+(4.25/100) .
you should use casting in System.out.println (double to int) --
(int)(futureInvestmentValue * 100) / 100.0

Categories