2017-04-07 71 views
0

我想区分多个令牌。
看看我的代码。使用说明javacc令牌

TOKEN : 
{ 
    < LOOPS : 
    <BEAT> 
    | <BASS> 
    | <MELODY> 
    > 
| < #BEAT : "beat" > 
| < #BASS : "bass" > 
| < #MELODY : "melody" > 
} 

void findType(): 
{Token loops;} 
{ 
loops = <LOOPS> 
{ String type = loops.image; } 

我想使用findType()函数来查找类型。
当输入是“节拍”时,我怎样才能得到正确的输出?

回答

1

你想要做的是增加一个return语句,就像这样:

String findType(): 
{Token loops;} 
{ 
    loops = <LOOPS> 
    { 
     String type = loops.image; 
     return type; 
    } 
} 

有想法,你已经在改变方法的返回值的定义,从voidString

然后,从主:

ExampleGrammar parser = new ExampleGrammar(System.in); 
    while (true) 
    { 
     System.out.println("Reading from standard input..."); 
     System.out.print("Enter loop:"); 
     try 
     { 
     String type = ExampleGrammar.findType(); 
     System.out.println("Type is: " + type); 
     } 
     catch (Exception e) 
     { 
     System.out.println("NOK."); 
     System.out.println(e.getMessage()); 
     ExampleGrammar.ReInit(System.in); 
     } 
     catch (Error e) 
     { 
     System.out.println("Oops."); 
     System.out.println(e.getMessage()); 
     break; 
     } 
    } 

它会产生类似的输出:

Reading from standard input... 
Enter loop:bass 
Type is: bass 
Reading from standard input... 
Enter loop:beat 
Type is: beat 
+0

对不起。 我试图简单地写,所以我写错了。 该函数的返回值已经是一个字符串 我很好奇的是令牌的定义。 当我如上所述定义'LOOPS'时,返回值没有出现。 –