I am trying to convert a string that the user inputs (price) to a double (price1) and assign it to a total price variable. Then I will convert it back to a string and store it in a map. I have copied the code I have written so far.
public class SalesTax {
public static void main(String[] args) {
// Input items for shopping cart
HashMap<String, String> cart = new HashMap<String, String>();
HashMap<String, String> shoppingcart = new HashMap<String, String>();
// Create a Scanner
Scanner input = new Scanner(System.in);
// variables
char done;
boolean goods;
double totalprice = 0;
double totalwtax = 0;
double totaltax;
// Pick items for list.
do {
System.out.print("Please enter an item.");
String item = input.nextLine();
System.out.print("Please enter the price for "+ item + ": ");
String price = input.nextLine();
double price1 = Double.parseDouble(price);
totalprice += price1;
String price2 = String.valueOf(price1);
shoppingcart.put(item, price2);
cart.put(item, price);
//determine if item will have additional tax
if (item.contains("music") == true)
{
double newprice = Double.parseDouble(price);
newprice = newprice *1.10;
totalwtax +=newprice;
String newprice2 = String.valueOf(newprice);
shoppingcart.put(item, newprice2);
}
else if (item.contains("imported") == true)
{
double newprice = Double.parseDouble(price);
newprice = newprice *1.05;
totalwtax +=newprice;
String newprice2 = String.valueOf(newprice);
shoppingcart.put(item, newprice2);
}
else if(item.contains("bottle") == true)
{
double newprice = Double.parseDouble(price);
newprice = newprice *1.10;
totalwtax +=newprice;
String newprice2 = String.valueOf(newprice);
shoppingcart.put(item, newprice2);
}
else
{
shoppingcart.put(item, price);
}
System.out.print("Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.");
done = input.nextLine().charAt(0);
totaltax = totalprice - totalwtax;
} while(Character.toUpperCase(done) == 'Y');
System.out.println("Your cart contains the following at items with tax" + shoppingcart);
System.out.println("Total Tax: " + totalwtax);
}
}
Test Case
The problem is that I'm not getting the total with tax if I input 12.49, 14.99, 0.85 and a 10% tax is on the 14.99 the total of all three should come out to be 29.83:
Please enter an item.standard
Please enter the price for standard: 12.49
Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.y
Please enter an item.music
Please enter the price for music: 14.99
Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.y
Please enter an item.discount
Please enter the price for discount: 0.85
Would you like to continue to add items? (Type Y) for Yes and (Type N) for No.n
Your cart contains the following at items with tax{music=16.489, standard=12.49, discount=0.85}
Total Tax: 16.489
Why does this code produce the wrong answer?