2017-02-21 22 views
-1

我正在製作詞法分析器。 LINE 1-30是導入 FUNCTION init()只是初始化關鍵字的HASHTABLE。 LINE 61的枚舉「TokenType」指定要採取的令牌。 當我清楚地聲明NUMBER時,出現錯誤,說沒有名稱組。 LINE 96使用匹配器引擎進行匹配。 LINE 97如果一個組匹配@ LINE 98,則創建一個令牌並返回,並且匹配器繼續前進到下一個。編譯器爲什麼說沒有名稱爲<NUMBER>的組?

public static enum TokenType{ 
    ADDSUB("[+|-]?"),NUMBER("-?[0-9]+"), 
INCDEC("[[++]|[--]]"),DIVMOD("[/|%]"), 
ID("[_a-zA-Z][_a-zA-Z0-9]*"), 
MUL("[*]+"), WHITESPACE("[ \t\f\r\n]+"); 
public final String pattern; 

    private TokenType(String pattern){ 
    this.pattern=pattern; 
    } 
    } 
    /*we declare a data structure for holding the token data*/ 
    public static class Token{ 
    public TokenType type; 
    public String Data; 
    public Token(TokenType type,String Data){ 
     this.type=type; 
     this.Data=Data; 
    } 
    @Override 
    public String toString() { 
    return String.format("(%s %s)", type.name(), Data); 
    } 
    } 

    public static ArrayList<Token> lex(String input) { 
// The tokens to return 
     ArrayList<Token> tokens = new ArrayList<Token>(); 

// Lexer logic begins here 
     StringBuffer tokenPatternsBuffer = new StringBuffer(); 
     for(TokenType tokenType :TokenType.values()){ 
     tokenPatternsBuffer.append(String.format("|(?<%s>%s)", tokenType.name(), tokenType.pattern)); 

    Pattern tokenPatterns=Pattern.compile(tokenPatternsBuffer.substring(1)); 
     // Begin matching tokens 
     Matcher matcher = tokenPatterns.matcher(input); 
      while(matcher.find())  
    {if(matcher.group(TokenType.NUMBER.name())!=null){ tokens.add(new Token(TokenType.NUMBER,matcher.group(TokenType.NUMBER.name()))); 
     continue; 
    } else if(matcher.group(TokenType.ID.name())!=null){ 
     if(KW.containsValue(matcher.pattern())){ 
      System.out.println("y"); 

tokens.add(new Token(TokenType.ID,matcher.group(TokenType.ID.name()))); 
     } 
     else{ 
      System.out.println("n"); 

tokens.add(newToken(TokenType.ID,matcher.group(TokenType.ID.name()))); 
     continue; 
     } 
    } 
     } 

    } 
    return tokens; 
      } 
+2

而不是*描述*您的代碼,*發佈*它。這對每個人來說都會更簡單。 – Guy

+1

看起來像一些語法錯誤,因爲枚舉TokenType在public final String模式之前有大括號。 – jatanp

+0

@Guy我已附上完整代碼 –

回答

2
public static enum TokenType{ 



    ADDSUB("[+|-]?"),NUMBER("-?[0-9]+"), 
    INCDEC("[[++]|[--]]"),DIVMOD("[/|%]"), 
    ID("[_a-zA-Z][_a-zA-Z0-9]*"), 
    MUL("[*]+"), WHITESPACE("[ \t\f\r\n]+"); 


    public final String pattern; 

    private TokenType(String pattern){ 
     this.pattern=pattern; 
    } 
} 

如上所示代碼更正

+1

問題保持不變 –

相關問題