HashMap初始化NullPointerException

时间:2014-03-08 06:54:21

标签: java nullpointerexception hashmap

控制台指向“变量”行上的空指针异常:

variable = spritePanel.getVariables();
    for(String s: variable.keySet()){
        sb.append(s);
        sb.append(variable.get(s));
        sb.append("<br>");          
    }

在我的代码顶部,我有:

public HashMap<String,Double> variable = new HashMap<String,Double>();

spritePanel是同一个包中另一个类的实例,方法getVariables()返回一个HashMap。

高级感谢您的帮助。

编辑 - 所以这是整个方法:

private String formatVariables() {

    spritePosition = spritePanel.getSpritePosition(0);
    double xcoor = spritePosition.getX();
    double ycoor = spritePosition.getY();
    double direc = spritePosition.getDirection();
    boolean pendown = spritePosition.getIsPenDown();
    boolean visibility = spritePosition.getIsHiding();

    StringBuffer sb = new StringBuffer();
    sb.append("<html><p align=left>");
    sb.append("X = ");
    sb.append(xcoor);
    sb.append("<br>");
    sb.append("Y = ");
    sb.append(ycoor);
    sb.append("<br>");
    sb.append("Direction = ");
    sb.append(direc);
    sb.append("<br>");
    sb.append("PenDown = ");
    sb.append(pendown);
    sb.append("<br>");
    sb.append("Sprite Hidden = ");
    sb.append(visibility);
    sb.append("<br>");

            //sb.append("</p></html>");
            //before I added the variable HashMap, the string buffer code worked


    variable = spritePanel.getVariables();  //this is where it breaks according to the console
    for(String s: variable.keySet()){
        sb.append(s);
        sb.append(variable.get(s));
        sb.append("<br>");          
    }

    sb.append("</p></html>");
    return sb.toString();       
}

1 个答案:

答案 0 :(得分:0)

这只表示执行variable = spritePanel.getVariables();时spritePanel为null。当变量设置为null并且您尝试使用该变量调用方法时,Java会抛出该异常。为了可视化,该行将像这样执行:variable = null.getVariables();其中null没有名为getVariables()的方法。尝试调查spritePanel何时变为空。