简体   繁体   中英

Getting the total of user input doubles

I am having trouble getting the total price to update correctly. I am inputting book = 12.49 music cd = 14.99 and chocolate bar = 0.85. What is happening is that the 14.99 * .10 is adding and the chocolate bar. It is erasing the first value of 12.49.

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.00;
    double taxprice;

    // 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;

        //System.out.println(String.format("%.2f",totalprice));
        String price2 = String.valueOf(price1);
        cart.put(item, price2);

        //determine if item will have additional tax
        if (item.contains("music"))
        {
            double newprice = Double.parseDouble(price);
            taxprice = newprice * .10;

            totalprice = (newprice + taxprice);

            //System.out.println(String.format("%.2f",totalprice));
            String newprice2 = String.valueOf(String.format("%.2f", totalprice));
            shoppingcart.put(item,newprice2);
        }
        else if (item.contains("imported"))
        {
            double newprice = Double.parseDouble(price);
            newprice = newprice * .05;

            totalprice += newprice;
            //System.out.println(String.format("%.2f",totalprice));
            String newprice2 = String.valueOf(String.format("%.2f", newprice));
            shoppingcart.put(item, newprice2);
        }
        else if(item.contains("bottle"))
        {
            double newprice = Double.parseDouble(price);
            newprice = newprice * .10;

            totalprice += newprice;
            System.out.println(String.format("%.2f",totalprice));
            String newprice2 = String.valueOf(String.format("%.2f", 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);
    } while(Character.toUpperCase(done) == 'Y');

   System.out.println("Your cart contains the following at items with tax" + shoppingcart); //+ String.format("%.2f", totalprice));
   System.out.println(String.format("%.2f",totalprice));
}

}

You add the value of the price of the item to the total cost here:

       double price1 = Double.parseDouble(price);
        totalprice += price1;

yet you do it again here.

        if (item.contains("music") == true)
        {
            double newprice = Double.parseDouble(price);
            newprice = newprice * 1.10;

            totalprice += newprice;

As a result, your total price includes the original price of the CD (without tax) added to the price with tax. In a way you are double counting the cost of the CD (but one time with tax and one time without).

I would recommend changing the if (item.contains("music") == true) block of code to

newprice = newprice * .10

and you should achieve the desired result. If you make this change I strongly recommend you change the names of the variables so that they indicate purpose (for instance, after my change the "newprice" variable actually is indicative of the tax, rather than an updated price).

In this code:

        if (item.contains("music") == true)
        {
            double newprice = Double.parseDouble(price);
            newprice = newprice * 1.10;

            totalprice += newprice;
            //System.out.println(String.format("%.2f",totalprice));
            String newprice2 = String.valueOf(String.format("%.2f", newprice));
            shoppingcart.put(item,newprice2);
        }

The value 1.10 should be 0.10, because you have already added the price of the music cd above, now you only need to add the tax. With the value 1.10 you are adding the price of the cd (again) plus the tax.

Lots of problems - this code doesn't compile. No main method, for starters.

You compare Strings with ==; you should be using equals.

The proper idiom for true/false checks is to use a boolean.

Wrong in lots of other ways.

I think something like this would be much cleaner. It has the additional advantage of calculating the total correctly.

package misc;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

/**
 * SalesTax description here
 * @author Michael
 * @link https://stackoverflow.com/questions/25351880/getting-the-total-of-user-input-doubles/25352033#25352033
 * @since 8/17/2014 1:51 PM
 */
public class ShoppingCart {

    private Map<String, Double> items;
    private Map<String, Double> taxRates;

    public ShoppingCart(Map<String, Double> taxRates) {
        this.items = new HashMap<>();
        this.taxRates = new HashMap<>();
        if (taxRates != null) {
            this.taxRates.putAll(taxRates);
        }
    }

    public void addItem(String name, double price) {
        double priceWithTax = (this.isTaxable(name) ? price*this.getTaxRate(name) : price);
        this.items.put(name, priceWithTax);
    }

    public boolean isTaxable(String name) {
        return this.taxRates.containsKey(name);
    }

    public double getTaxRate(String name) {   
        return (this.isTaxable(name) ? this.taxRates.get(name) : 1.0);
    }

    public double getTotal() {
        double total = 0.0;
        for (String name : items.keySet()) {
            total += items.get(name);
        }
        return total;
    }

    public static void main(String[] args) {
        // Create a Scanner
        Scanner input = new Scanner(System.in);
        Map<String, Double> taxRates = new HashMap<String, Double>() {{
            put("music", 1.10);
            put("imported", 1.05);
        }};
        ShoppingCart shoppingCart = new ShoppingCart(taxRates);
        String line;
        do {
            System.out.print("Enter name, price or Q to quit: ");
            line = input.nextLine();
            String [] tokens = line.split(",");
            if ((tokens.length > 1)) {
                shoppingCart.addItem(tokens[0], Double.parseDouble(tokens[1]));
            }
        } while (!"Q".equalsIgnoreCase(line));
        System.out.println(String.format("%.2f", shoppingCart.getTotal()));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM