-1
我有一个购物清单,其中包含一定数量的项目。通过用户输入,我想询问用户他们想要添加到他们的购物袋中的多少相同的物品。如何将重复值添加到ArrayList
例如:我有以下ArrayList newProduct = {"apple","orange","banana"};
。现在我想要提示用户选择newProduct中的哪些项目(以及多少项)是否希望添加到名为bag
的第二个数组中。如果用户选择数量为2的苹果,则2个苹果将被添加到bag
,并且看起来像这样bag = {"apple","apple"};
我试图使用会重复该值的操作。但它不太好。这有什么问题?
import java.util.*;
import java.util.stream.IntStream;
public class Bag extends Price {
static Scanner input = new Scanner(System.in);
@SuppressWarnings("unused")
private static String newName;
private int choice;
public ArrayList<String> bag = new ArrayList<String>();
public List<Double> bagPrice = new ArrayList<Double>();
public void addProduct() {
Bag item = new Bag();
while (sum(bagPrice) <= 58.00) {
System.out.println("Choose a Priority");
item.choice = input.nextInt();
System.out.println("Choose Quantity");
int quantity = input.nextInt();
if (IntStream.of(newPriority).anyMatch(x -> x == item.choice)) {
item.bag.add(newProduct.get(item.choice));
System.out.print("PRICE $ " + Double.valueOf(formatter.format(price.get(item.choice - 1))));
bagPrice.add(price.get(item.choice - 1));
System.out.println("BAG: " + item.bag);
System.out.println("TOTAL : " + Double.valueOf(formatter.format(sum(bagPrice))));
} else {
System.out.println("Priority Does Not Exist");
}
}
}
public double sum(List<Double> bagPrice) {
double sum = 0.00;
for (double s : bagPrice) {
sum = sum + s;
}
return sum;
}
}
我是相当新的编程,所以如果有任何更好的建议,我将不胜感激。
除非这是一个任务,一个更好的建立也只是使用'Map'使用的产品名称为关键和数量作为价值。 – Carcigenicate
这是不是很清楚你在这里问什么。你能告诉我们你的完整代码吗?特别是定义了'Bag','sum()'和'newPriority'。 –
它看起来像一个任务。但我相信谁给了你这个练习并不意味着你认为他的意思。仔细阅读你的指示,然后使用HashMap。 –
auval