【问题标题】:Java: Update an existing entry in products map: update the count of the purchases of this productJava:更新产品地图中的现有条目:更新该产品的购买次数
【发布时间】:2018-04-05 02:17:28
【问题描述】:

我需要使用 ProductId HashMap 插入或更新 txt 文件的条目。我不熟悉HashMap。即使 TreeSet 也可以工作,我也必须使用 HashMap。我知道我必须使用迭代器,但我不知道如何。该文件在控制台中读取,因此没有问题。

问题: 我需要参考某个 productID 键(即 1005)来将 ItemPrice 更新为 90 美元。

public class StoreSales {


public static void main(String[] args) {
    List<Customer> customer = new ArrayList<>();

    try {

        readFile("Sales.txt", customer);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
    System.out.println(customer);

}

public static void readFile(String file, List<Customer> cust) throws IOException, ClassNotFoundException {
    Map<Integer, Customer> CustomerID = new HashMap<>();
    Map<Integer, Customer> ProductID = new HashMap<>();
    try (BufferedReader in = new BufferedReader(new FileReader(file))) {
        String line;
        while ((line = in.readLine()) != null) {
            String[] arr = line.split(" ");
            cust.add(new Customer(Integer.parseInt(arr[0]), arr[1], arr[2], Integer.parseInt(arr[3]), arr[4], Double.parseDouble(arr[5]), Integer.parseInt(arr[6])));

            if (CustomerID.containsKey(Integer.parseInt(arr[0]))) {
                CustomerID.get(arr[0]).getItemsPurchased();

            }
            if (ProductID.containsKey(Integer.parseInt(arr[3]))) {
                ProductID.get(arr[3]).getSingleItemPrice();

            }
        }
    }

}

}

【问题讨论】:

  • 我没有看到明确的问题陈述。至少指出哪几行代码有问题。
  • 我更新了问题
  • 最简单的方法是重写整个文件。

标签: java hashmap iterator


【解决方案1】:

您的问题需要进一步澄清

I need to insert or update an entry for a txt file using the ProductId HashMap.

如果您希望执行上述操作,则需要使用 BufferedWriter 写入文件。使用 HashMap 的概念非常简单实际 HashMap --> 首先理解概念,把它想象成一个银行/储物柜来获取你需要的有价值的物品/物品的钥匙,hashMap 的工作原理就是这样

现在,如果您只需要值
for(String str:map.values())
在您的情况下
for(Customer cust:ProductID.values()) // 获取地图中存在的所有客户值

根据您编写的代码,我假设这是因为您没有提供完整的代码,但您没有为您的 Map 分配任何值,因此您不会获得任何数据,您甚至可能会得到一个例外

只有在需要键值对值时才需要迭代

for (Map.Entry<Integer, Customer> entry : ProductID.entrySet()) System.out.println("Key = " + entry.getKey() + ", Customer = " + entry.getValue());

希望这有帮助, 快乐编码:)

【讨论】:

    【解决方案2】:

    Problem: I need to reference to a certain productID key (which is 1005) to update the ItemPrice to $90

    if (ProductID.containsKey(1005)) { ProductID.get(1005).setSingleItemPrice(90); }

    请更具体地说明你下次想要什么:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-30
      • 1970-01-01
      • 2016-12-03
      • 2023-03-10
      • 2023-04-02
      • 2013-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多