2017-09-25 88 views
1

这是我一直在使用的代码,我从here(从第13页开始;我可以成功执行并解析来自input.txt文件的附加示例,其中包含数字和+迹象sintactically正确即4 + 2 returns six,但4 ++ 2 gives an errorjavaCC解析器生成器无法处理EOF

options { 
    STATIC = false ; 
} 

PARSER_BEGIN (Calculator) 
    import java.io.PrintStream ; 

class Calculator 
{ 
    public static void main (String [] args) 
    throws ParseException, TokenMgrError, NumberFormatException 
    { 
     Calculator parser = new Calculator(System.in) ; 
     parser.Start(System.out) ; 
    } 
    double previousValue = 0.0 ; 
} 
PARSER_END (Calculator) 

SKIP : { " " } 
TOKEN : { < EOL : "\n" | "\r" | "\r\n" > } 
TOKEN : { < PLUS : "+" > } 
TOKEN : { < NUMBER : <DIGITS> | <DIGITS> "." <DIGITS> | <DIGITS> "." | "." <DIGITS> > } 
TOKEN : { <#DIGITS : (["0"-"9"])+ > } 

void Start(PrintStream printStream) throws NumberFormatException : 
{} 
{ 
    (
     previousValue = Expression() 
     <EOL> 
     {printStream.println(previousValue) ; } 
    )* 
    <EOF> 
} 

double Expression() throws NumberFormatException : 
{ 
    double i ; 
    double value ; 
} 
{ 
    value = Primary() 
    (
     <PLUS> 
     i = Primary() 
     { value += i ; } 
    )* 
    { return value ; } 
} 

double Primary() throws NumberFormatException : 
{ 
    Token t ; 
} 
{ 
    t = <NUMBER> 
    { return Double.parseDouble(t.image) ; } 
} 

'

C:\Users\Jay\workspace\javaCC>javacc calculator0.jj 

生成所有必需的Java文件正确,所有那些我编译没有错误,也没有警告与

javac *.java 

但后来,当我尝试运行

java Calculator < input.txt 

其中input.txt中含有

4 + 2 + 2

由于某种原因,在这个新版本我得到

Exception in thread "main" ParseException: Encountered "<EOF>" at line 1, column 11. 
Was expecting one of: 
    <EOL> ... 
    "+" ... 

     at Calculator.generateParseException(Calculator.java:218) 
     at Calculator.jj_consume_token(Calculator.java:156) 
     at Calculator.Start(Calculator.java:27) 
     at Calculator.main(Calculator.java:10) 

我该如何解决这个问题?

+0

语法每行需要一个表达式。这是一个蓄意的设计决定。也许教程可以更好地解释这个决定。 –

回答

1

我找到了解决方案。这是PDF上的一个小错误,我能够解决它。只需要添加三个字符来修复该错误。

答案是改变:

void Start(PrintStream printStream) throws NumberFormatException : 
{} 
{ 
    (
     previousValue = Expression() 
     <EOL> 
     {printStream.println(previousValue) ; } 
    )* 
    <EOF> 
} 

void Start(PrintStream printStream) throws NumberFormatException : 
{} 
{ 
    (
     previousValue = Expression() 
     (<EOL>)* 
     {printStream.println(previousValue) ; } 
    )* 
    <EOF> 
} 

它就像一个魅力。

+0

“bug”一词似乎有点苛刻。 :-) –

+0

是的。唯一的问题是'Expression'可以在他们之间没有任何''这在原始版本中是不允许的。 –