Search code examples
javaeclipseiojavacc

How can I change javaCC adder.jj to receive a String instead of a stream from command prompt?


I created adder.jj file following this tutorial (till page 13, just before it starts with the calculator example), to create an adder, which works great for obtaining the result of numbers and plus sign in a syntactically correct way (e.g. "4+3 +7" returns 14, while "4++3" gives an error), those numbers and + signs come from a text file (this is explained in a bit). The code I use to generate the needed classes to do what is explained before.

options
{
    STATIC = false ;
}
PARSER_BEGIN(Adder)
    class Adder
    {
        public static void main (String[] args)
        throws ParseException, TokenMgrError, NumberFormatException 
        {
            Adder parser = new Adder (System.in) ;
            int val = parser.Start() ;
            System.out.println(val) ;
        }
    }
PARSER_END(Adder)

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

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

int Primary() throws NumberFormatException :
{
    Token t ;
}
{
    t=<NUMBER>
    { return Integer.parseInt( t.image ) ; }
}

The classes are generated with

javacc adder.jj

Then I compile the generated classes with

javac *.java

And finally

java Adder < ex1.txt

Gives the right output if the content of ex1.txt has the format I explained before.

How can I change this code to receive a String so I can actually use it in my project instead of the stream from the command line?


Solution

  • Try replacing

    Adder parser = new Adder (System.in) ;
    

    with

    Reader reader = new StringReader( someString ) ;
    Adder parser = new Adder( reader ) ;