java 计算器 的实现

阅读更多
java 代码
  1. import java.math.BigDecimal;   
  2. import java.util.HashMap;   
  3. import java.util.Iterator;   
  4. import java.util.Stack;   
  5. import java.util.StringTokenizer;   
  6.   
  7. public class Expression {   
  8.        
  9.     public static void main(String[] args) {   
  10.            
  11.         String expres = "c*d+(((a+67.32)+(c-39))/d+10)";   
  12. //      expres = "11*13+(((13+67.32)+(13-39))/56+23)";   
  13.                    
  14.         HashMap variables = new HashMap();     
  15.         variables.put("a",new BigDecimal("10"));   
  16.         variables.put("b",new BigDecimal("20"));   
  17.         variables.put("c",new BigDecimal("30"));   
  18.         variables.put("d",new BigDecimal("40"));   
  19.            
  20.         Expression calc = new Expression(variables,expres);   
  21. //      calc = new Ccl(null,expres);   
  22.            
  23.         double resut = calc.getResult().doubleValue();   
  24.         System.out.println(" Expression = "+expres);   
  25.         calc.printVariables();   
  26.         System.out.println(" Result = " + resut);   
  27.            
  28.     }   
  29.   
  30.   
  31.     //----------   
  32.     private String expression;   
  33.     private HashMap operators = new HashMap();     
  34.     {          
  35.         operators.put("+""1");   
  36.         operators.put("-""1");   
  37.         operators.put("/""2");   
  38.         operators.put("*""2");   
  39.         operators.put("(""0");                   
  40.     }      
  41.     private Context ctx;       
  42.        
  43.        
  44.     public Expression(HashMap vars,String expr) {   
  45.         ctx = new Context(vars);   
  46.         expression = expr;   
  47.     }   
  48.        
  49.     public BigDecimal getResult() {   
  50.            
  51.         //infix to Postfix   
  52.         String pfExpr = infixToPostFix(toVaviable(expression));   
  53.   
  54.         //build the Binary Tree   
  55.         Expressions rootNode = buildTree(pfExpr);   
  56.   
  57.         //Evaluate the tree   
  58.         return rootNode.evaluate(ctx).setScale(2,BigDecimal.ROUND_HALF_UP);   
  59.            
  60.     }   
  61.   
  62.     private NonTerminalExpression getNonTerminalExpression(   
  63.         String operation,   
  64.         Expressions l,   
  65.         Expressions r) {   
  66.         if (operation.trim().equals("+")) {   
  67.             return new AddExpression(l, r);   
  68.         }   
  69.         if (operation.trim().equals("-")) {   
  70.             return new SubtractExpression(l, r);   
  71.         }   
  72.         if (operation.trim().equals("*")) {   
  73.             return new MultiplyExpression(l, r);   
  74.         }   
  75.         if (operation.trim().equals("/")) {   
  76.             return new DivExpression(l, r);   
  77.         }   
  78.         return null;   
  79.     }   
  80.   
  81.   
  82.        
  83.     private String toVaviable(String str){   
  84.         char var = 'z';   
  85.         StringBuffer tmp = new StringBuffer();   
  86.            
  87.         StringTokenizer st = new StringTokenizer(str, "+-*/()"true);   
  88.         String ss = null;   
  89.         while (st.hasMoreElements()) {   
  90.             ss = st.nextToken();   
  91.                
  92.             if(isDigital(ss)){                 
  93.                 ctx.assign((var)+"",ss);   
  94.                 tmp.append((var)+"");   
  95.                 var--;   
  96.             }else{   
  97.                 tmp.append(ss);   
  98.             }   
  99. //          System.out.println(ss);   
  100.         }   
  101.            
  102.         return tmp.toString();   
  103.     }   
  104.        
  105.     private String infixToPostFix(String str) {   
  106.         Stack s = new Stack();   
  107.         String pfExpr = "";   
  108.         String tempStr = "";   
  109.   
  110.         String expr = str.trim();   
  111.         for (int i = 0; i < str.length(); i++) {   
  112.   
  113.             String currChar = str.substring(i, i + 1);   
  114.   
  115.             if ((isOperator(currChar) == false)   
  116.                 && (!currChar.equals("("))   
  117.                 && (!currChar.equals(")"))) {   
  118.                 pfExpr = pfExpr + currChar;   
  119.             }   
  120.             if (currChar.equals("(")) {   
  121.                 s.push(currChar);   
  122.             }   
  123.             //for ')' pop all stack contents until '('   
  124.             if (currChar.equals(")")) {   
  125.                 tempStr = (String) s.pop();   
  126.                 while (!tempStr.equals("(")) {   
  127.                     pfExpr = pfExpr + tempStr;   
  128.                     tempStr = (String) s.pop();   
  129.                 }   
  130.                 tempStr = "";   
  131.             }   
  132.             //if the current character is an   
  133.             // operator   
  134.             if (isOperator(currChar)) {   
  135.                 if (s.isEmpty() == false) {   
  136.                     tempStr = (String) s.pop();   
  137.                     String strVal1 = (String) operators.get(tempStr);   
  138.                     int val1 = new Integer(strVal1).intValue();   
  139.                     String strVal2 = (String) operators.get(currChar);   
  140.                     int val2 = new Integer(strVal2).intValue();   
  141.   
  142.                     while ((val1 >= val2)) {   
  143.                         pfExpr = pfExpr + tempStr;   
  144.                         val1 = -100;   
  145.                         if (s.isEmpty() == false) {   
  146.                             tempStr = (String) s.pop();   
  147.                             strVal1 = (String) operators.get(tempStr);   
  148.                             val1 = new Integer(strVal1).intValue();   
  149.   
  150.                         }   
  151.                     }   
  152.                     if ((val1 < val2) && (val1 != -100))   
  153.                         s.push(tempStr);   
  154.                 }   
  155.                 s.push(currChar);   
  156.             } //if   
  157.   
  158.         } // for   
  159.            
  160.         while (s.isEmpty() == false) {   
  161.             tempStr = (String) s.pop();   
  162.             pfExpr = pfExpr + tempStr;   
  163.         }   
  164.            
  165.         return pfExpr;   
  166.     }   
  167.        
  168.     private Expressions buildTree(String expr) {   
  169.         Stack s = new Stack();   
  170.   
  171.         for (int i = 0; i < expr.length(); i++) {   
  172.             String currChar = expr.substring(i, i + 1);   
  173.   
  174.             if (isOperator(currChar) == false) {   
  175.                 Expressions e = new TerminalExpression(currChar);   
  176.                 s.push(e);   
  177.             } else {   
  178.                 Expressions r = (Expressions) s.pop();   
  179.                 Expressions l = (Expressions) s.pop();   
  180.                 Expressions n = getNonTerminalExpression(currChar, l, r);   
  181.                 s.push(n);   
  182.             }   
  183.         } //for   
  184.         return (Expressions) s.pop();   
  185.     }      
  186.        
  187.     private boolean isDigital(String str) {   
  188.         if (!isOperator(str) && !ctx.checkKey(str) && !isComma(str))   
  189.             return true;   
  190.         return false;   
  191.     }   
  192.        
  193.     private boolean isComma(String str) {   
  194.         if ((str.equals("("))   
  195.             || (str.equals(")")))   
  196.             return true;   
  197.         return false;   
  198.     }   
  199.        
  200.     private boolean isOperator(String str) {   
  201.         if ((str.equals("+"))   
  202.             || (str.equals("-"))   
  203.             || (str.equals("*"))   
  204.             || (str.equals("/")))   
  205.             return true;   
  206.         return false;   
  207.     }   
  208.        
  209.     public void printVariables(){   
  210.         this.ctx.print();   
  211.     }   
  212. // End of class   
  213.   
  214. class Context {   
  215.        
  216.     private HashMap varList = new HashMap();   
  217.   
  218.     public void assign(String var, String value) {   
  219.         varList.put(var, new BigDecimal(value));   
  220.     }   
  221.   
  222.     public BigDecimal getValue(String var) {   
  223.         BigDecimal  tmp;   
  224.         if(varList.get(var) == null){   
  225.             tmp = new BigDecimal(var);   
  226.         }else{   
  227.             tmp = (BigDecimal) varList.get(var);   
  228.         }   
  229.            
  230. //      System.out.println(var+ " "+tmp.doubleValue());   
  231.            
  232.         return tmp;   
  233.     }   
  234.        
  235.     public boolean checkKey(String var){   
  236.            
  237.         return varList.get(var) == null?false:true;   
  238.            
  239.     }   
  240.     public void print(){   
  241.         Object ob ;   
  242.         for(Iterator it = varList.keySet().iterator();it.hasNext();){   
  243.             ob = it.next();   
  244.             System.out.println(ob+" = "+varList.get(ob));   
  245.         }   
  246.     }   
  247.            
  248.     public Context(HashMap vars) {   
  249.         if(vars !=null)   
  250.             varList = vars;   
  251.     }   
  252.        
  253. }   
  254.   
  255.   
  256. class TerminalExpression implements Expressions {   
  257.        
  258.     private String var;   
  259.   
  260.     public TerminalExpression(String v) {   
  261.         var = v;   
  262.     }   
  263.   
  264.     public BigDecimal evaluate(Context c) {   
  265.         return c.getValue(var);   
  266.     }   
  267. }   
  268.   
  269.   
  270. interface Expressions {   
  271.     public BigDecimal evaluate(Context c);   
  272. }   
  273.   
  274.   
  275.   
  276. abstract class NonTerminalExpression implements Expressions {   
  277.     private Expressions leftNode;   
  278.   
  279.     private Expressions rightNode;   
  280.   
  281.     public NonTerminalExpression(Expressions l, Expressions r) {   
  282.         setLeftNode(l);   
  283.         setRightNode(r);   
  284.     }   
  285.   
  286.     public void setLeftNode(Expressions node) {   
  287.         leftNode = node;   
  288.     }   
  289.   
  290.     public void setRightNode(Expressions node) {   
  291.         rightNode = node;   
  292.     }   
  293.   
  294.     public Expressions getLeftNode() {   
  295.         return leftNode;   
  296.     }   
  297.   
  298.     public Expressions getRightNode() {   
  299.         return rightNode;   
  300.     }   
  301. // NonTerminalExpression   
  302.   
  303.   
  304.   
  305. class AddExpression extends NonTerminalExpression {   
  306.     public BigDecimal evaluate(Context c) {   
  307.         return getLeftNode().evaluate(c).add(getRightNode().evaluate(c));   
  308.     }   
  309.   
  310.     public AddExpression(Expressions l, Expressions r) {   
  311.         super(l, r);   
  312.     }   
  313. // AddExpression   
  314.   
  315.   
  316.   
  317. class SubtractExpression extends NonTerminalExpression {   
  318.     public BigDecimal evaluate(Context c) {   
  319.         return getLeftNode().evaluate(c).subtract(getRightNode().evaluate(c));   
  320.     }   
  321.   
  322.     public SubtractExpression(Expressions l, Expressions r) {   
  323.         super(l, r);   
  324.     }   
  325. // SubtractExpression   
  326.   
  327.   
  328.   
  329. class MultiplyExpression extends NonTerminalExpression {   
  330.     public BigDecimal evaluate(Context c) {   
  331.         return getLeftNode().evaluate(c).multiply(getRightNode().evaluate(c));   
  332.     }   
  333.   
  334.     public MultiplyExpression(Expressions l, Expressions r) {   
  335.         super(l, r);   
  336.     }   
  337. //    
  338.   
  339.   
  340.   
  341. class DivExpression extends NonTerminalExpression {   
  342.     public BigDecimal evaluate(Context c) {   
  343.         return getLeftNode().evaluate(c).divide(getRightNode().evaluate(c),4,BigDecimal.ROUND_HALF_UP);   
  344.     }   
  345.   
  346.     public DivExpression(Expressions l, Expressions r) {   
  347.         super(l, r);   
  348.     }   
  349.   
  350. //   

你可能感兴趣的:(Java,C,C++,C#,UP)