我正在尝试更新 HashMap
并直接在下一个方法中使用它,但它不起作用。从我读到的内容来看,我找不到解决方案。有人说这是不可能的,有人说使用迭代器,但即使使用迭代器它也不起作用。错误是打印方法,它没有打印,甚至没有进入 while 循环,因为它是空的,但我找不到原因
这是我尝试更新和打印一些信息的两种方法。
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class OrderList {
// Storage for an arbitrary number of details.
private HashMap<String, Order> orderList = new HashMap<String, Order>();
/**
* Perform any initialization .
*/
public OrderList() {
orderList = new HashMap<String, Order>();
}
public HashMap<String, Order> getOrders() {
return orderList;
}
public void readOrderFile(String OrderListPath) {
try {
File file = new File(OrderListPath);
Scanner scan = new Scanner(file);
while (scan.hasNextLine()) {
String readLine = scan.nextLine();
if (readLine != null) {
getSplitLinesOrders(readLine);
}
}
} catch (Exception e) {
}
}
public void getSplitLinesOrders(String readLine) {
String id = "";
String customerId = "";
String itemId = "";
int quantity = 0;
try {
String[] splitedLine = readLine.split(",");
if (splitedLine.length == 4) {
id = splitedLine[0];
customerId = splitedLine[1];
itemId = splitedLine[2];
quantity = Integer.parseInt(splitedLine[3]);
Order newOrder = new Order(id, customerId, itemId, quantity);
orderList.put(id, newOrder);
}
} catch (Exception e) {
}
}
/**
* Add a new set of details to the list
* @param details The details of the staff
*/
// public void addDetails(Order details) {
// orderList.add(details);
// }
public boolean hasOrder() {
return orderList.size() != 0;
}
public Order getNextOrder() {
Order order = orderList.remove(0);
return order;
}
/**
* @return All the details
*/
public String listDetails() {
StringBuffer allEntries = new StringBuffer();
for (Map.Entry<String, Order> details : orderList.entrySet()) {
String Key = details.getKey();
Object value = details.getValue();
allEntries.append(Key + " " + value);
}
return allEntries.toString();
}
public void PrintListOfOrders() {
Iterator it = getOrders().entrySet().iterator();
try {
while (it.hasNext()) {
Order value = (Order) it.next();
System.out.println(value.getOrderId() + " " + value.getCustomerId() + " " + value.getItemId() + " " + value.getQuantity());
}
} catch (Exception e) {
System.out.println(e);
}
}
}
最佳答案
您可能会遇到NullPointerException
?下次告诉我们出了什么问题,并提供堆栈跟踪(如果适用)。
您发布的代码不会创建 orderList
的实例,因此,如果未在其他地方完成该操作,该代码将抛出 NullPointerException
尝试添加:
private HashMap<String, Order> orderList = new HashMap<String, Order>;
像这样吞掉异常
:
} catch (Exception e) {
}
这不是一个好的做法,因为它会隐藏有关问题所在的所有信息,至少这样做:
catch (Exception e) {
e.printStacktrace();
}
关于Java HashMap的创建、编辑和删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9252856/