【发布时间】: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();
}
}
}
}
}
【问题讨论】:
-
我没有看到明确的问题陈述。至少指出哪几行代码有问题。
-
我更新了问题
-
最简单的方法是重写整个文件。