开发者

Null Pointer Exception: null error [duplicate]

This question already has answers here: What is a NullPointerException, and how do I fix it? (12 answers) Closed 6 years ago.

I have this Hash Set code and when I try to run my compile method on it I get the Null Pointer Exception: null error on it. Here is the code:

private void initKeywords() {
        keywords = new HashSet<String>();
        keywords.add("final");
        keywords.add("int");
        keywords.add("while");
        keywords.add("if");
        keywords.add("else");
        keywords.add("print");     
    }

    private boolean isIdent(String t) {
        if (keywords.contains(t)) {  ***//This is the line I get the Error***
            return false;
        }
        else if (t != null && t.length() > 0 && Character.isLetter(t.charAt(0))) {
            return true;
        }
        else {
            return false;
        }
    }

The other lines that goes along with this error is:

public void compileProgram() {        
        System.out.println("compiling " + filename);
        while (theToken != null) {
            if (equals(theToken, "int") || equals(theToken, "final")) {
                compileDeclaration(true);
            } else {
                compileFunction(); //This line is giving an error with the above error
            }
        }
        cs.emit(Machine.HALT);
        isCompiled = true;
  开发者_运维技巧  }



private void compileFunction() {
        String fname = theToken;
        int entryPoint = cs.getPos();  
        if (equals(fname, "main")) {
            cs.setEntry(entryPoint);
        } 
        if (isIdent(theToken)) theToken = t.token(); ***//This line is giving an error***
        else t.error("expecting identifier, got " + theToken);

        symTable.allocProc(fname,entryPoint);


       accept("(");
        compileParamList();
        accept(")");
        compileCompound(true);
        if (equals(fname, "main")) cs.emit(Machine.HALT);
        else cs.emit(Machine.RET);
    }


Are you sure you're running initKeywords() before isIdent()?


Either keywords or t is null. Using either a debugger or print statements it should be pretty simple to determine. If keywords is null, I'd assume that initKeywords() has not been called yet.


You probably want to call initKeywords from the constructor of this object.


I personally try to stay away from init methods. As previously mentioned, a constructor serves as an initializer, and so does the static block:

private final static Set<String> KEYWORDS = new HashSet<String>();
static {
        keywords.add("final");
        keywords.add("int");
        keywords.add("while");
        keywords.add("if");
        keywords.add("else");
        keywords.add("print");
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜