1

I'm trying to learn Java, and came across a problem on one of the exercises listed in the book that I'm using. The exercise asks for me to make use of the ArrayLists to create a program that simulates a shopping cart. I've got everything up and running, however, when I try to add up the grand total finalPrice, I get a number that is way off. Any help would be great.

import java.util.ArrayList;
import java.util.Scanner;

public class Shop1 {
    public static void main(String[]args) {
        ArrayList < Item > cart = new ArrayList();

        Item item;
        String itemName;
        double itemPrice;
        int quantity;
        double finalPrice = 0;

        Scanner scan = new Scanner(System.in);

        String keepShopping = "y";

        do {
            System.out.print("Enter the name of the item: ");
            itemName = scan.next();

            System.out.print("Enter the unit price: ");
            itemPrice = scan.nextDouble();

            System.out.print("Enter the quantity: ");
            quantity = scan.nextInt();

            // create a new item and add it to the cart
            item = new Item(itemName, itemPrice, quantity);
            cart.add(item);

            for (int i = 0; i < cart.size(); i++) {
                Item temp = cart.get(i);
                System.out.println(temp);
                double subTotal =
                    ((temp.getPrice()) * (temp.getQuantity()));
                finalPrice += subTotal;

            }

            System.out.print("Continue shopping (y/n)? ");
            keepShopping = scan.next();
        } while (keepShopping.equals("y"));

        System.out.println("Please pay: $" + finalPrice);
    }
}

3 Answers 3

4

You're not clearing the 'finalPrice' variable before adding to it, so each time an item is added, you're starting with the 'finalPrice' from all the previous items and then adding from there.

finalPrice =0;
for (int i=0; i<cart.size(); i++)
{
    Item temp = cart.get(i);
    System.out.println(temp);
    double subTotal = ((temp.getPrice()) * (temp.getQuantity()));
    finalPrice += subTotal;
}

Since the counter 'i' isn't actually needed in this case, you can also write the code more succinctly as...

finalPrice =0;
for (Item temp: cart)
{
    System.out.println(temp);
    double subTotal = ((temp.getPrice()) * (temp.getQuantity()));
    finalPrice += subTotal;
}

But... since you're updating the final price after each item, you don't need to iterate through the entire list each time an item is added. You just need to add the price of the most recent item to the current total, so you could simply replace...

for (int i=0; i<cart.size(); i++)
{
    Item temp = cart.get(i);
    System.out.println(temp);
    double subTotal = ((temp.getPrice()) * (temp.getQuantity()));
    finalPrice += subTotal;

}

With

finalPrice += itemPrice * quantity;
Sign up to request clarification or add additional context in comments.

2 Comments

I did not get the logic of the last part of your answer: is the whole for statement reduced to that one line or what?
The 'for' loop is inside the 'do-while' loop. So each time a new item is added, he's going through the entire list and adding up the prices of all items. That really isn't necessary. All he really has to do is figure out the cost of the most recent item and add it to the running total. Another option would have been to move the entire 'for' loop outside the 'do-while' loop, right after 'while (keepShopping.equals("y"));', but before 'System.out.println("Please pay: $" + finalPrice);'
0

It looks like you don't reset finalPrice to zero before adding up all the items in the cart. Your code will work the first time, but not if you keep shopping.

Comments

0

You need to zero-out finalPrice before entering your loop, otherwise it will increase [somewhat] exponentially with each iteration.

...
finalPrice = 0;
for (int i=0; i<cart.size(); i++)
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.