2017-04-07 75 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'時,返回值沒有出現。 –