利用JAVACC实现简单的四则运算

it2024-12-05  20

代码

/** * JavaCC template file created by SF JavaCC plugin 1.5.28+ wizard for JavaCC 1.5.0+ */ options { static = true; } PARSER_BEGIN(Calculator) package calculator; import java.io.*; public class Calculator { public static void main(String args []) throws NumberFormatException,ParseException,TokenMgrError,FileNotFoundException { FileInputStream fis = new FileInputStream("src/calculator/input.txt"); System.setIn(fis); Calculator parser = new Calculator(System.in); parser.Start(System.out); } static double previousValue = 0.0; } PARSER_END(Calculator) SKIP : {" "} TOKEN : /* OPERATORS */ { < PLUS : "+" > | < MINUS : "-" > | < MULTIPLY : "*" > | < DIVIDE : "/" > } TOKEN : { < EOL : "\n" | "\r" | "\r\n"> } TOKEN : { < NUMBER : < DIGITS> | < DIGITS> "." < DIGITS> | < DIGITS> "." | "." < DIGITS> > | < #DIGITS : ([ "0"-"9" ])+ > } TOKEN : { < OPEN_PAR : "("> | < CLOSE_PAR : ")"> | < PREVIOUS : "$"> } void Start(PrintStream printstream) throws NumberFormatException: {} { ( previousValue = Expression() < EOL > { printstream.println(previousValue);} )* < EOF > } double Expression() throws NumberFormatException: { double i; double value; } { value = Term() ( < PLUS > i = Term() { value += i;} | < MINUS > i = Term() { value -= i;} )* { return value; } } double Term() throws NumberFormatException: { double i; double value; } { value = Primary() ( < MULTIPLY > i = Primary() { value *= i;} | < DIVIDE > i = Primary() { value /= i;} )* { return value;} } double Primary() throws NumberFormatException: { Token t; double d; } { t = < NUMBER > { return Double.parseDouble(t.image); } | < PREVIOUS > { return previousValue; } | < OPEN_PAR> d = Expression() < CLOSE_PAR> { return d;} | < MINUS > d = Primary() { return -d;} }

学到了什么

如何用正则表达式来进行词法分析从而得到Tokens,以及如何跳过无用的空白符如何利用JAVACC的action功能得到语义值捡起来了快忘记的markdown语法

参考资料

超好用的入门教程不知道说了些啥的官方文档

转载于:https://www.cnblogs.com/tclan126/p/9240667.html

相关资源:数据结构—成绩单生成器
最新回复(0)