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);
}
}
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.
Since the counter ‘i’ isn’t actually needed in this case, you can also write the code more succinctly as…
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…
With