发表新主题 回复该帖子
主题:[转]java重写eval方法
唧唧
帖子档案  楼主 [转]java重写eval方法   Post by : 2009-10-08 15:21:28.0
  • 幼儿园
  • 幼儿园
  • UID:3
  • 主题:342
  • 帖子:781
  • 加为好友 加为好友    发送短信 发送短信
   java代码
  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3. import java.util.Stack;  
  4.  
  5. public class Eval {  
  6.  
  7.     public static void main(String[] arg) throws Exception {  
  8.         String exp = "1+2*10+38-5";  
  9.         Eval eval = new Eval();  
  10.         List<String> list = eval.infixExpToPostExp(exp);// 转化成后缀表达式  
  11.         String result = eval.doEval(list);// 真正求值  
  12.         System.out.println(exp + "=" + result);  
  13.     }  
  14.  
  15.     // 遇到操作符压栈,遇到表达式从后缀表达式中弹出两个数,计算出结果,压入堆栈  
  16.     private String doEval(List<String> list) throws Exception {  
  17.         Stack<String> stack = new Stack<String>();  
  18.         String element;  
  19.         double n1, n2, result;  
  20.         try {  
  21.             for (int i = 0; i < list.size(); i++) {  
  22.                 element = list.get(i).toString();  
  23.                 if (isOperator(element)) {  
  24.                     n1 = Double.parseDouble(stack.pop() + "");  
  25.                     n2 = Double.parseDouble(stack.pop() + "");  
  26.                     result = doOperate(n2, n1, element);  
  27.                     stack.push(result + "");  
  28.                 } else {  
  29.                     stack.push(element);  
  30.                 }  
  31.             }  
  32.             return "" + stack.pop();  
  33.         } catch (RuntimeException e) {  
  34.             throw new Exception(e.getMessage());  
  35.         }  
  36.     }  
  37.  
  38.     private double doOperate(double n1, double n2, String operator) {  
  39.         if (operator.equals("+"))  
  40.             return n1 + n2;  
  41.         else if (operator.equals("-"))  
  42.             return n1 - n2;  
  43.         else if (operator.equals("*"))  
  44.             return n1 * n2;  
  45.         else 
  46.             return n1 / n2;  
  47.     }  
  48.  
  49.     private boolean isOperator(String str) {  
  50.         return str.equals("+") || str.equals("-") || str.equals("*")  
  51.                 || str.equals("/");  
  52.     }  
  53.  
  54.     private List<String> infixExpToPostExp(String exp) throws Exception {// 将中缀表达式转化成为后缀表达式  
  55.         exp = exp + "#";  
  56.         List<String> postExp = new ArrayList<String>();// 存放转化的后缀表达式的链表  
  57.         StringBuffer numBuffer = new StringBuffer();// 用来保存一个数的  
  58.         Stack<String> opStack = new Stack<String>();// 操作符栈  
  59.         char ch;  
  60.         String preChar;  
  61.         opStack.push("#");  
  62.         try {  
  63.             for (int i = 0; i < exp.length();) {  
  64.                 ch = exp.charAt(i);  
  65.                 switch (ch) {  
  66.                 case '+':  
  67.                 case '-':  
  68.                 case '*':  
  69.                 case '/':  
  70.                     preChar = opStack.peek().toString();  
  71.                     // 如果栈里面的操作符优先级比当前的大,则把栈中优先级大的都添加到后缀表达式列表中  
  72.                     while (priority(preChar.charAt(0)) >= priority(ch)) {  
  73.                         postExp.add("" + preChar);  
  74.                         opStack.pop();  
  75.                         preChar = opStack.peek().toString();  
  76.                     }  
  77.                     opStack.push("" + ch);  
  78.                     i++;  
  79.                     break;  
  80.                 case '(':  
  81.                     // 左括号直接压栈  
  82.                     opStack.push("" + ch);  
  83.                     i++;  
  84.                     break;  
  85.                 case ')':  
  86.                     // 右括号则直接把栈中左括号前面的弹出,并加入后缀表达式链表中  
  87.                     String c = opStack.pop().toString();  
  88.                     while (c.charAt(0) != '(') {  
  89.                         postExp.add("" + c);  
  90.                         c = opStack.pop().toString();  
  91.                     }  
  92.                     i++;  
  93.                     break;  
  94.                 // #号,代表表达式结束,可以直接把操作符栈中剩余的操作符全部弹出,并加入后缀表达式链表中  
  95.                 case '#':  
  96.                     String c1;  
  97.                     while (!opStack.isEmpty()) {  
  98.                         c1 = opStack.pop().toString();  
  99.                         if (c1.charAt(0) != '#')  
  100.                             postExp.add("" + c1);  
  101.                     }  
  102.                     i++;  
  103.                     break;  
  104.                 // 过滤空白符  
  105.                 case ' ':  
  106.                 case '\t':  
  107.                     i++;  
  108.                     break;  
  109.                 // 数字则凑成一个整数,加入后缀表达式链表中  
  110.                 default:  
  111.                     if (Character.isDigit(ch) || ch == '.') {  
  112.                         while (Character.isDigit(ch) || ch == '.') {  
  113.                             numBuffer.append(ch);  
  114.                             ch = exp.charAt(++i);  
  115.                         }  
  116.                         postExp.add(numBuffer.toString());  
  117.                         numBuffer = new StringBuffer();  
  118.                     } else {  
  119.                         throw new Exception("illegal operator");  
  120.                     }  
  121.                 }  
  122.             }  
  123.         } catch (RuntimeException e) {  
  124.             throw new Exception(e.getMessage());  
  125.         }  
  126.         return postExp;  
  127.     }  
  128.  
  129.     private int priority(char op) throws Exception {// 定义优先级  
  130.         switch (op) {  
  131.         case '+':  
  132.         case '-':  
  133.             return 1;  
  134.         case '*':  
  135.         case '/':  
  136.             return 2;  
  137.         case '(':  
  138.         case '#':  
  139.             return 0;  
  140.         }  
  141.         throw new Exception("Illegal operator");  
  142.     }  

运行结果:1+2*10+38-5=54.0

转自:http://blog.csdn.net/pp156/archive/2009/03/16/3995010.aspx

签名
 ★★★★★★★★
 纵里寻她千百度,蓦然回首,那人却在,灯火阑珊处!
 MyBlog :http://blog.javawind.net
返回页面顶部  


CopyRight © 2008-2009 JavaWind.Net Studio All Rights Reserved
Powered By JWind.BBS Vesion 1.0.0 Beta1 Processed in 30 ms,0 (Queries)  Gzip enabled

WAP - 清除Cookies - 联系我们 - JavaWind.Net Studio - Archiver - TOP Valid XHTML 1.0 Transitional Valid CSS! 粤ICP备07511478号