Frage

    

Diese Frage bereits eine Antwort hier:

         

Ich habe diesen Hash-Set-Code und wenn ich versuche, meine Kompilierung-Methode auf, um sie auszuführen ich die Null-Zeiger-Ausnahme erhalten: null Fehler auf sie. Hier ist der 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;
        }
    }

Die anderen Linien, die zusammen mit diesem Fehler geht, sind:

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);
    }
War es hilfreich?

Lösung

Entweder keywords oder t ist null. Entweder mit einem Debugger oder print-Anweisungen sollte es ziemlich einfach sein, zu bestimmen. Wenn keywords null ist, würde ich davon ausgehen, dass initKeywords() noch nicht genannt.

Andere Tipps

Sind Sie sicher, dass Sie laufen initKeywords() vor isIdent()?

Sie wollen wahrscheinlich initKeywords aus den Konstruktor dieses Objekt aufzurufen.

Ich persönlich versuche zu bleiben weg von init Methoden. Wie bereits erwähnt, dient ein Konstruktor als initializer, und so auch der statische 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");
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top