Package Excel;
Import java.util.nosuchelementexception; import java.util.StringTokenizer;
Public class calculator {private stringtokenizer t;
Private static final int mc_symb = 1; private static final int mc_num = 2; private static final int mc_none = 0; private static final int mc_eot = -1;
Private int mcode; // tokencode private char msymb; // token value private double mnum; // token value
Private Double Result;
/ ** * konstruktor constructor * /
public Calculator (String input) throws SyntaxErrorException {T = new StringTokenizer (input, " - * / () / t", true); MCode = MC_NONE; Result = expr (); if (MCode = MC_EOT!) throw new SyntaxErrorException ();
/ ************************************************** ************************* * RETURns the Calculated Value of the Expression ************************* *********************************************************** ******** /
Public Double getResult () {return result;}
/ ************************************************** ********************************** * The lexer to prduce a token when mcode is mc_none ************* *********************************************************** *********** /
Private boolean lex () throws syntaxerrorexception {string token; if (mcode == mc_none) {mcode = mc_eot; msymb = '/ 0'; mnum = 0.0; try {do token = T.NEXTTOKEN (); while (token.equals (") || token.equals (" / t "));} catCHelementExcection E) {Return False;} // Numeral.Igit (TOKEN.CHARAT (0))) {INT i; for (i = 0; i
Private Double Expr () THROWS SYNTAXERROREXCEPTION {Double TMP = Term (); while (lex () && mcode == mc_symb && (msymb == ' ' || msymb == '-')) {mcode = mc_none; = MSYMB == ' ') TMP = TERM (); else tmp - = term ();} if (mcode == mc_symb && msymb == '(' || mcode == mc_symb && msymb == ')' | |}; **************************************************** * Term IMPLEments the Rule < Term> ->
Private Double Term () THROWS SYNTAXERROREXCEPTION {Double TMP = FAC (); while (lex () && mcode == mc_symb && (MSYMB == '*' || msymb == '/')) {mcode = mc_none; if ( MSYMB == '*') TMP * = FAC (); Else TMP / = FAC ();} Return TMP;}
/ ************************************************** ************************* * FAC IMPLEMENTS The Rule
Private Double Fac () THROWS SYNTAXERROREXCEPTION {Double Tmp; Boolean Minus = FALSE
IF (lex () && mcode == mc_symb && msymb == '-') {mcode = mc_none; minus = true;} if (lex () && mcode == mc_symb && msymb == '(') {mcode = mc_none TMP = expr (); if (lex () && mcode! = Mc_symb || msymb! = ') ")") (); Mcode = mc_none;} else = mc_num) {mcode = mc_none; TMP = mnum;} else throw new syntaxerrorException (); if (minus) TMP = -tmp; returnTMP;}}