两年没做开发了,java也忘得差不多了,刚才想做个小东西,遇到困难了!看如下代码段:int a = 1;
ing b = 2;
int c = 3;String d = "+";
String e = "*";我想要的是运算公式:1+2*3=?
因为运算符是由用户输入的,而且运算的个数也不一定,可能还会出现减法和除法,请问怎么实现!

解决方案 »

  1.   

    有这么麻烦的,用到栈,转成后缀再处理
    import java.util.*;public class CalStr {
    private String src;

    /**
     * constructor
     * @param src the string(expression) to calculate
     */
    public CalStr(String src) {
    this.src = src;
    }
    /**
     * calculate to get the result
     * @return (double)result
     */
    public double getResult() {
    String postfix = getPostfix();
    Stack<String> stk = new Stack<String>();
    //System.out.println(postfix);
    String parts[] = postfix.split(" +");
    double result=0;
    for(int i=0; i<parts.length; i++){
    char tmp = parts[i].charAt(0);
    if(!isOperator(tmp)){
    stk.push(parts[i]);
    }
    else{
    double a = Double.parseDouble(stk.pop());
    double b = Double.parseDouble(stk.pop());
    //b is followed by a in the orignal expression
    result = calculate(b,a,tmp);
    stk.push(String.valueOf(result));
    }
    }
    return result;
    }
    /**
     * test if the character is an operator,such +,-,*,/
     * @param op the character to test
     * @return true if op is an operator otherwise false
     */
    private boolean isOperator(char op){
    return (op=='+'||op=='-'||op=='*'||op=='/');
    }


    /**
     * calculate an expression such (a op b)
     * @param a number 1
     * @param b number 2
     * @param op the operator
     * @return (double)(a op b)
     */
    public double calculate(double a, double b, char op) {
    switch (op) {
    case '+':
    return a + b;
    case '-':
    return a - b;
    case '*':
    return a * b;
    case '/':
    return a / b;
    }
    return -1;
    }
    /**
     * convert the suffix to postfix
     * @return the postfix as a string
     */
    private String getPostfix() {
    Stack<String> stk = new Stack<String>();
    String postfix = new String();
    char op;
    int i = 0;
    while (i < src.length()) {
    if (Character.isDigit(src.charAt(i))||src.charAt(i)=='.') {
    postfix += " ";
    do {
    postfix += src.charAt(i++);
    } while ((i < src.length())
    && (Character.isDigit(src.charAt(i))));
    postfix += " ";
    } else {
    switch (op = src.charAt(i++)) {
    case '(':
    stk.push("(");
    break;

    case ')':
    while (stk.peek() != "(") {
    String tmp = stk.pop();
    postfix += tmp;
    if(tmp.length()==1 && isOperator(tmp.charAt(0)))
    postfix += " ";
    }
    stk.pop();
    postfix += " ";
    break;

    case '+':
    case '-':
    while ((!stk.empty()) && (stk.peek() != "(")) {
    postfix += stk.pop()+" ";
    }
    stk.push(new Character(op).toString());
    break;

    case '*':
    case '/':
    while ((!stk.empty())
    && ((stk.peek() == "*") || (stk.peek() == "/"))) {
    postfix += stk.pop()+" ";
    }
    stk.push(new Character(op).toString());
    break;
    }
    }
    }
    ListIterator it = stk.listIterator(stk.size());
    while (it.hasPrevious())
    postfix += it.previous() + " ";
    return postfix.trim().replaceAll(" +\\.",".");
    } /**
     * main function
     * @param args
     */
    public static void main(String args[]) {
    System.out.println(new CalStr("((1.5+6.000)*9+9.36)*(8+9-8*8+8*7)").getResult());
    }
    }
      

  2.   

    写完善也很麻烦的,《C++ 程序设计语言》中有一个完整的例子,需要改成 JAVA 语言。晚上我看看有空没。:)
      

  3.   

    三楼的,Stack<String> stk = new Stack<String>();怎么报错!
      

  4.   

    Stack<String> stk = new Stack<String>();
    这个是jdk1.5泛型的写法
    如果你是1.5以前的,改成Stack stk = new Stack();
    后面get的时候强制转换为String
      

  5.   

    我测试过了,绝对通过,希望能给你带来方便:
    package test;
    import java.io.*;
    import java.util.*;
    import java.sql.*;
    public class testBean
    {
         public int a = 1;
         public int b = 2;
         public int c = 3;     public String d = "+";
         public String e = "*";     public String getResult()
        {
            String sTemp = "";
             sTemp = a+d+b+e+c;
             String str1 = sTemp.substring(0,sTemp.indexOf("+"));
             String str2 = sTemp.substring((sTemp.indexOf("+")+1),sTemp.indexOf("*"));
             String str3 = sTemp.substring((sTemp.indexOf("*")+1));
             
             int nResult = ((Integer.parseInt(str1))+(Integer.parseInt(str2))*(Integer.parseInt(str3)));
             String sResult = String.valueOf(nResult);
              return sResult;
         }
    }
    class testBeanMain extends testBean
     {
          public static void main(String [] args)
          {
               testBean tb = new testBean();
               System.out.println("The Result is : "+tb.getResult());
          }
     }
      

  6.   

    重点是达到目的,能赚钱就行!Understand?
      

  7.   

    取出+,-,×,/,的asscii值,来对应是很准确的
      

  8.   

    class a
    {
    char str;
    int b1,b2;
    public int setstr(int b1,char str,int b2)
    {
    this.str=str;
    this.b1=b1;
    this.b2=b2;
    if(str=='+')
    {
    return b1+b2;
    }
    if(str=='-')
    {
    return b1-b2;
    }
    if(str=='*')
    {
    return b1*b2;
    }
    if(str=='/')
    {
    return b1/b2;
    }
    return 0;
    }public static void main(String[] args)
    {
    a a1=new a();
    int b1=3,b2=4;
    System.out.println(a1.setstr(b1,'*',b2));
    }
    }
      

  9.   

    回复人: sunman511(JAVA狂人傻瓜版) 你那只是两个数的运算,100个数的怎么做?
      

  10.   

    我是来看believefym(暮色,miss,迷失,miss)的
      

  11.   

    看一眼:http://www.sz3000.com/index.htm?QQ=822982
      

  12.   

    人气不错呀,合适的时候我就结贴,我用的是JDK1.4,believefym(暮色,miss,迷失,miss)的方法一直没调通!
      

  13.   

    还像不用如此麻烦,非用堆栈吗.
    在写一个表单,就可以,加上BEAN 用JSP完成任务.
      

  14.   

    我顶!中国IT人才网(    http://www.itbbs.net.cn    )!中国IT人才网(    http://www.itbbs.net.cn    )!中国IT人才网(    http://www.itbbs.net.cn    )!中国IT人才网(    http://www.itbbs.net.cn    )!中国IT人才网(    http://www.itbbs.net.cn    )!中国IT人才网(    http://www.itbbs.net.cn    )!中国IT人才网(    http://www.itbbs.net.cn    )!中国IT人才网(    http://www.itbbs.net.cn    )!中国IT人才网(    http://www.itbbs.net.cn    )!中国IT人才网(    http://www.itbbs.net.cn    )!中国IT人才网(    http://www.itbbs.net.cn    )!
    免费招聘、求职。IT人工作的天堂。希望能够为大家所用。
      

  15.   

    参考
    http://www.javaresearch.org/article/showarticle.jsp?column=31&thread=26059