rascal K
rascal K

Reputation: 11

directions for use javacc token

I want to distinguish multiple tokens.
Look at my code.

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

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

I want to use the findType () function to find the type.
How can I get return the correct output when the input is "beat"?

Upvotes: 0

Views: 172

Answers (1)

CheshellCat
CheshellCat

Reputation: 51

What you want to do is to add a return statement, like this:

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

Have in mind you have changed return value definition in the method, from void to String.

Then, from your main:

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

It generates an output like:

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

Upvotes: 1

Related Questions