【问题标题】:Java: Using a key from the ProductID HashMap, update the count of the purchases of this productJava:使用 ProductID HashMap 中的键,更新该产品的购买次数
【发布时间】:2018-04-05 05:13:57
【问题描述】:

应在产品地图中使用键 5020 更新条目,将购买次数增加 2。

我不确定如何使用 ProductID.put 对我拥有的 Sales.txt 文件的条目进行必要的更改。文件的内容显示完美,但我不知道如何使用更改更新文件。

我认为我需要在某些时候使用迭代器。但我对HashMap不熟悉。

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]).getSingleItemPrice();

            }
            if (ProductID.containsKey(Integer.parseInt(arr[3]))) {
                ProductID.get(arr[3]).getItemsPurchased();
                **this is the problem** //ProductID.put(, 2++);


            }
        }
    }

}

}

【问题讨论】:

  • 您永远不会在任何一个地图(CustomerID、ProductID)中放置任何东西。地图总是
  • ProductID 是整数和客户的映射。这个 Customer 类是什么样的?

标签: java hashmap iterator


【解决方案1】:

从地图中获取对象将为您提供可以操作的对象的引用。

Customer c = ProductID.get(arr[3]);
c.setItemsPurchased(c.getItemsPurchased() + 2);

但就像 Nishit 在 cmets 中指出的那样,if 语句将永远是错误的,因为您从未在映射中放置任何东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-30
    • 2021-03-17
    • 2016-12-03
    • 2023-03-10
    • 2019-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多