javacc 计算器 实例

options {
 STATIC=false;
}
PARSER_BEGIN(calculator)

import java.io.PrintStream ;
public class calculator {
 double previousValue = 0.0 ;
 public static void main(String args[]) throws ParseException {
  calculator parser = new calculator(System.in);
  while (true) {
   System.out.println("This is an advanced calculator based on the prior .jj embeded in eclipse");
   System.out.print("Enter an expression like \"2.0+3.4 \" we support +,-,*,\\,(),sin(),cos(),and number with fraction:");
   try {
    parser.Start(System.out);


   } catch (Exception e) {
    System.out.println("NOK.");
    System.out.println(e.getMessage());
    parser.ReInit(System.in);
   } catch (Error e) {
    System.out.println("Oops.");
    System.out.println(e.getMessage());
    break;
   }
  }
 }
}
PARSER_END(calculator)

SKIP :
{
  " "
 
}


TOKEN : { /* OPERATORS */
< PLUS: "+"
 >
| < MINUS: "-"
 >
| < MULTIPLY: "*"
 >
| < DIVIDE: "/"
 >
|   < LPAREN : "("
 >
|   < RPAREN : ")"
 >
|   < NUMBER :
 <DIGITS> | <DIGITS> "." <DIGITS> | <DIGITS> "." | "."<DIGITS> >
|   < #DIGITS : (["0"-"9"])+ >
|   < SIN: "sin"
 >
|   < COS: "cos"
 >
|   <  EOL : "\n"
 | "\r" | "\r\n" >
}

void Start(PrintStream printStream)  :
{}
{
 (
     previousValue = sum()
                     <EOL>
 { printStream.println( previousValue ) ; }
 )*
 <EOF>
}

 

double  sum() : {
 double i;
 double value=0.0;
}
{
 value=term()(<PLUS>i=term() {
  value+=i;
 }|<MINUS> i=term() {
  value-=i;
 })*
 {return value;}

}

double term() : {
 double i;
 double value=0.0;
}
{
 value = Primary()(<MULTIPLY>i = Primary() {
  value *= i ;
 }|<DIVIDE>i = Primary() {
  value /= i ;
 })*
 { return value ;}

}
double Primary() : {
 Token t ;
 double value=0.0;
}
{
 t=<NUMBER> { return Double.parseDouble( t.image ) ; }
 |
 <LPAREN> value=sum() <RPAREN> { return value ; }
 |
 <MINUS> value=Primary() {
  return -value ;
 }
 |
 <SIN><LPAREN>value=sum()<RPAREN> {   return java.lang.Math.sin(value);   }
 |
 <COS><LPAREN>value=sum()<RPAREN> {  return java.lang.Math.cos(value);   }
}

 

 

你可能感兴趣的:(javacc 计算器 实例)