我正在尝试学习Java,并遇到了本书中列出的练习 中的一个问题。练习要求我使用 ArrayList
s创建一个模拟购物车的程序。我已经有 一切正常运行,但是,当我尝试总计 合计finalPrice
时,我得到一个数字是远离。任何帮助都会很棒。使用arraylist的总计
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);
}
}
非常有帮助的解释。谢谢! – Joel 2011-06-15 02:45:18
我没有得到你答案的最后部分的逻辑:整个“for”陈述简化为那一行还是什么? – mico 2011-06-15 18:57:06
'for'循环在'do-while'循环中。所以每次添加新物品时,他都会浏览整个清单并将所有物品的价格加起来。那真的没有必要。他真正需要做的就是计算最近项目的成本,并将其添加到运行总数中。 另一种选择是在'while(keepShopping.equals(“y”));'之后,但在'System.out.println(')之前将整个'for'循环移到'do-while' “请付:$”+ finalPrice);' – Mike 2011-06-16 18:20:24