【问题标题】:java.lang.NullPointerException Error [duplicate]java.lang.NullPointerException 错误 [重复]
【发布时间】:2014-04-07 02:00:34
【问题描述】:

我是 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;
    }

【问题讨论】:

    标签: java


    【解决方案1】:

    您通过在构造函数中重新声明 healthBenDesig 使类字段为空来隐藏它。不要重新声明它。

    改变

    public VariableList() {
        HashMap<String, Double> healthBenDesig = new HashMap<String, Double>();
    }
    

    到:

    public VariableList() {
        healthBenDesig = new HashMap<String, Double>();
    }
    

    【讨论】:

    • “谢谢”按钮是您在答案左侧看到的刻度线。它告诉所有人,您的问题已得到满意的答复,不需要进一步的答复。
    【解决方案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>();
        }
    

    【讨论】:

      【解决方案3】:

      您可以在属性声明中初始化 healthBenDesig

      private HashMap<String, Double> healthBenDesig = new HashMap<String, Double>();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-20
        • 2014-08-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-20
        • 1970-01-01
        • 2016-08-16
        • 2017-02-21
        相关资源
        最近更新 更多