[英]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 (eg "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). 我按照本教程(直到第13页,以计算器示例开始之前)创建了
adder.jj
文件,以创建一个加法器,该加法器非常适用于以语法正确的方式获取数字结果和加号(例如“ 4 +3 +7“返回14,而“ 4 ++ 3”给出错误),这些数字和+符号来自文本文件(对此将作一些说明)。 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. 如果
ex1.txt
的内容具有我之前解释的格式,则提供正确的输出。
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? 如何更改此代码以接收字符串,以便实际上可以在项目中使用它而不是从命令行使用流?
Try replacing 尝试更换
Adder parser = new Adder (System.in) ;
with 同
Reader reader = new StringReader( someString ) ;
Adder parser = new Adder( reader ) ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.