gpt4 book ai didi

java - 如何使用方法从 Map 返回值?

转载 作者:行者123 更新时间:2023-12-02 00:26:49 26 4
gpt4 key购买 nike

在这种情况下如何返回 int 值?

import java.util.*;

public class ShoppingCart {

private Map<String, Purchase> shoppingCart = new HashMap<String, Purchase>();

public void add (String product, int price) {
Purchase purchase = new Purchase(product, 1, price);
shoppingCart.put(product, purchase);
}

public int totalPrice() {
//How do I accomplish this? I want to return all the prices summed together

}
}
}

购买方法的构造函数是:

 public Purchase(String product, int amount, int price) {

最佳答案

您需要迭代 map 值和总价

例如,此代码将起作用。

 public int totalPrice() {
int sum = 0;
for(Purchase p:shoppingCart.values()){
sum+=p.getPrice();
}
return sum;
}

关于java - 如何使用方法从 Map 返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9838695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com