我一直在尝试创建一个方法来添加用户购买的所有物品,但找不到正确的代码。我已经制作了一个程序,可以打印用户想要购买的商品,但我似乎找不到合适的代码来添加所有商品的价格
Scanner in = new Scanner(System.in); boolean loopAgain = true; boolean cont = true; ArrayList<String> food = new ArrayList<>(); food.add("Pizza"); food.add("Burger"); food.add("Fries"); food.add("Taco"); ArrayList<Integer> cost = new ArrayList<>(); cost.add(160); cost.add(35); cost.add(25); cost.add(30); ArrayList<String> quant = new ArrayList<>(); while(loopAgain) { System.out.print("Beverage Available: "); for(int i=0; i<4; i++) { System.out.print(food.get(i)+ " = "+cost.get(i)+" "); if(i<food.size()-1) System.out.print(""); } // user input System.out.print("\nPurchase Beverage: "); String c = in.nextLine(); if(c.equalsIgnoreCase("pizza")) { quant.add(food.get(0) + "\t" + cost.get(0)); } else if(c.equalsIgnoreCase("burger")) { quant.add(food.get(1) + "\t" + cost.get(1)); } else if(c.equalsIgnoreCase("fries")) { quant.add(food.get(2) + "\t" + cost.get(2)); } else if(c.equalsIgnoreCase("taco")) { quant.add(food.get(3) + "\t" + cost.get(3)); } else { System.out.println("-Invalid-"); } System.out.print("\nDo you want to add more? Yes or No? "); String yn = in.nextLine(); if(yn.equalsIgnoreCase("yes")) { loopAgain = true; cont = false; } else if(yn.equalsIgnoreCase("no")) { loopAgain = false; cont = false; } else { System.out.println("-Invalid-"); } } **// this is to display the items purchased** System.out.println("\n>>Amount to pay<<\n"); for(int s=0; s<quant.size(); s++) { System.out.println(quant.get(s)); }
这是我迄今为止所做的。它不添加所显示项目的价格,而是只添加数组列表成本中给出的价格。
int sum = 0; for(int total:cost) { System.out.println("Total Amount: " + sum); sum = sum + total; } } }
我无法调用arraylist quant,因为它是字符串。如何添加用户购买的物品的价格?