0

このハッシュ セット コードがあり、それに対してコンパイル メソッドを実行しようとすると、Null Pointer Exception: null エラーが発生します。コードは次のとおりです。

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

このエラーに付随する他の行は次のとおりです。

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);
    }
4

4 に答える 4

2

initKeywords()前に実行していてisIdent()よろしいですか?

于 2009-12-08T01:37:03.910 に答える
0

initKeywordsおそらく、このオブジェクトのコンストラクターから呼び出したいでしょう。

于 2009-12-08T01:38:56.280 に答える
0

keywordsまたはnulltです。デバッガーまたは print ステートメントのいずれかを使用すると、非常に簡単に判断できます。null の場合、まだ呼び出されていないkeywordsと想定します。initKeywords()

于 2009-12-08T01:40:46.470 に答える
0

私は個人的に init メソッドを避けるようにしています。前述のように、コンストラクターは初期化子として機能し、静的ブロックも同様です。

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");
}
于 2009-12-08T05:55:16.113 に答える