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);
}
}