Reputation: 1
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?
Upvotes: 0
Views: 281
Reputation: 462
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;
Upvotes: 0
Reputation: 3042
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
.
Upvotes: 1
Reputation: 436
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;
Upvotes: 3