我是Java的初学者。&我一直收到这个错误..指向这一行的java.lang.NullPointerException - > Double hOption = healthBenDesig.get(" employeeOnly"); 有人可以告诉我,如果我错过了什么或者我究竟做错了什么吗?
private HashMap<String, Double> healthBenDesig;
public VariableList()
{
HashMap<String, Double> healthBenDesig = new HashMap<String, Double>();
}
public VariableList()
{
HashMap<String, Double> healthBenDesig = new HashMap<String, Double>();
}
public void getHMP()
{
Double hOption = healthBenDesig.get("employeeOnly");
System.out.println("The health Option you chose is: " + hOption);
}
public HashMap setHealthOpt()
{
healthBenDesig.put("none", 0.00);
healthBenDesig.put("employeeOnly", 311.87);
healthBenDesig.put("spouse", 592.56);
healthBenDesig.put("children", 717.30);
healthBenDesig.put("kids", 882.60);
System.out.println(healthBenDesig);
return healthBenDesig;
}
答案 0 :(得分:5)
您通过在构造函数中重新声明healthBenDesig,使类字段为null,从而隐藏了healthBenDesig。不要重新声明它。
更改
public VariableList() {
HashMap<String, Double> healthBenDesig = new HashMap<String, Double>();
}
为:
public VariableList() {
healthBenDesig = new HashMap<String, Double>();
}
答案 1 :(得分:2)
您没有初始化您的班级成员healthBenDesig,而是使用lcoal变量对其进行遮蔽。这导致healthBenDesig未初始化并导致NullPointerException
。你的构造函数,从
public VariableList()
{
// re-declaration or shadowing of memeber variable healthBenDesig
HashMap<String, Double> healthBenDesig = new HashMap<String, Double>();
}
到
public VariableList()
{
healthBenDesig = new HashMap<String, Double>();
}
答案 2 :(得分:0)
您可以在属性声明
初始化healthBenDesigprivate HashMap<String, Double> healthBenDesig = new HashMap<String, Double>();