2009-12-08 110 views
0

我有這個哈希集代碼,當我嘗試運行我的編譯方法時,我得到空指針異常: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); 
    } 
+0

嘿,請記住接受您的答案。 – ChaosPandion 2009-12-08 01:49:55

回答

0

keywordst爲空。使用調試器或打印語句,它應該很容易確定。如果keywords爲空,我認爲initKeywords()還沒有被調用。

2

你確定你isIdent()之前運行initKeywords()

0

您可能想從此對象的構造函數調用initKeywords

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