How do I fix the tax rate operation? - java

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;

Related

Calculate sales tax according to the price

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;

Program output is NaN instead of float

I am working on an exercise from a book, the exercise sounds like this:
Drivers are concerned with the mileage their automobiles get. One driver has kept track of several trips by recording the miles driven and gallons used for each tankful. Develop a Java application that will input the miles driven and gallons used (both as integers) for each trip. The program should calculate and display the miles per gallon obtained for each trip and print the combined miles per gallon obtained for all trips up to this point. All averaging calculations should produce floating-point results. Use class Scanner and sentinel-controlled repetition to obtain the data from the user.
Here is my code:
import java.util.Scanner;
public class consumption {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int miles = 0;
int gallons = 0;
int totalGallons = 0;
int totalMiles = 0;
float mpg = 0;
float totalAverage = 0;
System.out.println("Enter number of gallons or enter -1 to finish:");
gallons = in.nextInt();
while(gallons != -1)
{
gallons += totalGallons;
System.out.println("Enter the number of miles driven:");
miles = in.nextInt();
miles += totalMiles;
mpg = ((float)totalMiles/totalGallons);
System.out.printf("Total Miles per Gallon on this trip is %.2f\n", mpg);
System.out.println("Enter number of gallons:");
gallons = in.nextInt();
}
if(totalGallons!=0)
{
totalAverage = (float) totalMiles/totalGallons;
System.out.printf("Total consumption on all trips is %.2f\n", totalAverage);
}
else
System.out.println("You did not enter a valid gallon quantity\n");
}
}
For some reason, after I enter the sentinel (-1), the output shows NaN instead of the float number it should output.
Also, it does not calculate the totalAverage, not even showing NaN
This is the output:
Enter number of gallons or enter -1 to finish: 25
Enter the number of miles driven: 5
Total Miles per Gallon on this trip is NaN
Enter number of gallons: -1
You did not enter a valid gallon quantity
Process finished with exit code 0
Please help me :(
A NaN value typically arises when you divide zero by zero using floating operations. It is short for "not a number" and is used in some contexts where a computation produces a value that is nonsensical.
(NaN does not represent an infinite number! There is a different floating point value for that: INF).
The primitive operations that generate NaN values in Java are:
0.0 / 0.0
±INF / ±INF
0.0 * ±INF and ±INF * 0.0
INF + (-INF) and (-INF) + INF
INF - (INF) and (-INF) - (-INF)
Some java.lang.Math functions can also generate NaN values. For example, Math.sqrt(-1) produces a NaN.
Hint: take a look at where you are doing the calculation of mpg ... and how you are calculating the two values that the expression uses. Look at them carefully. (And check your lecture notes on what += actually does!)
Inside the while loop, you write the statements
gallons += totalGallons;
miles += totalMiles;
but totalGallons is initialized as 0 and its value never changes. The same is for totalMiles. Therefore the calculation for mpg
mpg = (float) totalMiles / totalGallons;
takes the form of
(float) 0/0;
which is infinity. In Java, infinity for float values is represented as Nan : Not a number. So just change the statements to
totalGallons += gallons;
totalMiles += miles;
EDIT
As the others have said, infinity is not Nan. There's a difference between when Java displays INF and when Nan. Refer to this question for more info: Difference between infinity and not-a-number.
Also, check #StephanC's answer on the cases where JAVA produces Nan.

Calculating Interest (Java), the program should print the projected account balance after an arbitrary numbers of years

Please help me. Basically the program should Ask the user to input a number representing the initial balance of a savings account. Assign this number to a double variable called balance.
Ask for a number representing the yearly rate of interest (in percent) on the account. Divide this number by 100.0 and assign it to a double variable called rate. I have to use a loop to update the balance as it changes year by year. I am stuck on that part. Here is the code I have so far :
public static void calcInterest(){
System.out.println("Please enter the account balance : ");
System.out.println("Please enter the annual interest rate : ");
System.out.println("Please enter the number of years : ");
Scanner input = new Scanner (System.in);
double balance = input.nextDouble();
double y = input.nextDouble();
double rate = (y/100);
int years = input.nextInt();
}
There's no good reason to use a loop in this case, but I guess it's for learning purposes.
You can make a loop that calculates the new balance a year at a time like this:
for(int i = years; i > 0; i--)
balance = balance * y;
Alternatively use Math.pow(this follows the formula startvalue * rate of change^time = result):
balance = balance * Math.pow(y, years);

How to create a savings bank system where program stops looping after balance doubles

I am a tasked to create a program that runs as described, programmed in Java:
Illustrate the growth of money in a savings account. The user enters the initial amount (as a decimal) and the interest rate which are used to calculate the number of years until the money doubles and the number of years until the money reaches a million dollars. (you will need to use more than 1 loop).
Note: The balance at the end of each year is
(1 + r) * balance
where balance is the previous balance, and r is the annual rate of interest in decimal form.
However, I cannot find the error in my code. What happens is that it continuously writes "Your balance will double in " and then the number infinitely grows.
Here is the code:
Scanner input = new Scanner(System.in);
double years = 0;
double futureVaule;
System.out.print("Please enter the amount of money you would like to deposit, as a decimal:\n>>");
double balance = input.nextDouble();
System.out.print("Please enter the interest rate of your deposit, as a percent:\n>>");
double r = input.nextDouble();
do
{
futureValue = (1 + r) * balance;
years = years + 1;
System.out.println("Your balance will double in "
+ Math.round(years) + " year(s).");
}while(futureValue <= balance*2);
This should work
futureValue = balance;
double doubleBalance = balance*2;
while(futureValue <= doubleBalance)
{
futureValue += futureValue * (( 1 + r)/100);
years++;
}
System.out.println("Your balance will double in "
+ years + " year(s).");

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