用javaCC实现double型数据的加减乘除法,正弦、余弦、正切、余切、反正弦、反余弦、反正切、反余
/** * JavaCC file */ options { JDK_VERSION = "1.5"; } PARSER_BEGIN(computer) package com.zju.edu; import java.math.*; public class computer { public static void main(String args[]) throws ParseException { computer parser = new computer(System.in); while (true) { System.out.println("Reading from standard input..."); System.out.print("Enter an expression like \"1+(2+3)*4/5+sin(1)*cos(2)*tan(3)/cot(4)+arcsin(0.4)*arccos(0.5)*arctan(5)/arccot(3)=\" :"); try { switch (computer.one_line()) { case 0: System.out.println("OK."); break; case 1: System.out.println("Goodbye."); break; default: break; } } catch (Exception e) { System.out.println("NOK."); System.out.println(e.getMessage()); computer.ReInit(System.in); } catch (Error e) { System.out.println("Oops."); System.out.println(e.getMessage()); break; } } } } PARSER_END(computer) SKIP : { " " | "\r" | "\t" | "\n" } TOKEN : /* OPERATORS */ { < PLUS: "+" > | < MINUS: "-" > | < MULTIPLY: "*" > | < DIVIDE: "/" > } TOKEN : { < CONSTANT: ( <DIGIT> )+ ("."(<DIGIT>)+)? > | < #DIGIT: ["0" - "9"] > } TOKEN:{ < SIN:"sin" > | < COS:"cos" > | < TAN:"tan" > | < COT:"cot" > | < ARCSIN:"arcsin" > | < ARCCOS:"arccos" > | < ARCTAN:"arctan" > | < ARCCOT:"arccot" > } int one_line() : { double a; } { a = sum() "=" {System.out.println(a); return 0; } | "=" { System.out.println("没有任何输入"); return 1; } } double sum() : { double a; double b; } { a = term() ( <PLUS> b=term() { a += b;} | <MINUS> b=term() { a-=b;} )* { return a;} } double term() : { double a; double b; } { a = unary() ( <MULTIPLY> b = unary() { a *= b;} | <DIVIDE> b = unary() { a /= b;} )* {return a;} } double unary() : { double a ; } { <MINUS> a = element() { return -a;} | a = element() { return a;} } double element() : { Token t; double a ; } { t = <CONSTANT> { return Double.parseDouble(t.toString()); } | <SIN> "(" t = <CONSTANT> ")" { return Math.sin(Double.parseDouble(t.toString()));} | <COS> "(" t = <CONSTANT> ")" { return Math.cos(Double.parseDouble(t.toString()));} | <TAN> "(" t = <CONSTANT> ")" { return Math.tan(Double.parseDouble(t.toString()));} | <COT> "(" t = <CONSTANT> ")" { return 1/Math.tan(Double.parseDouble(t.toString()));} | <ARCSIN> "(" t = <CONSTANT> ")" { return Math.asin(Double.parseDouble(t.toString()));} | <ARCCOS> "(" t = <CONSTANT> ")" { return Math.acos(Double.parseDouble(t.toString()));} | <ARCTAN> "(" t = <CONSTANT> ")" { return Math.atan(Double.parseDouble(t.toString()));} | <ARCCOT> "(" t = <CONSTANT> ")" { return ((Math.PI / 2) - Math.atan(Double.parseDouble(t.toString())));} | "(" a = sum() ")" { return a;} }