tags:

views:

100

answers:

4

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);
    }
+2  A: 

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

Anon.
A: 

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

ChaosPandion
A: 

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.

Colin Gislason
A: 

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");
}
Droo