计算器JAVA中式转逆波兰式算法

来源:互联网 发布:应届生考公务员知乎 编辑:程序博客网 时间:2024/04/28 13:16
/**
* 制作人:李金泉   学校:桂林工学院    QQ:55204816     邮箱:vip_ljq@yeah.net
* 在网上面看到一些例子,运行起来会出错,所以今天来修改一下,加了一些功能;
* 希望有助于大家学习
*/
package expression;
import java.io.*;  
import java.util.*;  
public class Expression
{
    private ArrayList expression = new ArrayList();// 存储中序表达式  
  
    private ArrayList right = new ArrayList();// 存储右序表达式  
  
    private String result;// 结果  
  
    // 依据输入信息创建对象,将数值与操作符放入ArrayList中  
    private Expression(String input)
    {  
        StringTokenizer st = new StringTokenizer(input, "+-*/()SCTL", true);  
        while (st.hasMoreElements())
        {  
            expression.add(st.nextToken());  
        }  
    }  
  
    // 将中序表达式转换为右序表达式  
    private void toRight()
    {  
        Stacks aStack = new Stacks();  
        String operator;  
        int position = 0;  
        while (true)
        {  
            if (Calculate.isOperator((String) expression.get(position)))
            {  
                if (aStack.top == -1 || ((String) expression.get(position)).equals("("))
                {  
                    aStack.push(expression.get(position));  
                }
                else
                {  
                    if (((String) expression.get(position)).equals(")"))
                    {  
                        if (!((String) aStack.top()).equals("("))
                        {  
                            operator = (String) aStack.pop();  
                            right.add(operator);  
                        }
                        //这里一定要注意了,千万不能漏,漏掉就有可能在括号的地方出错
                        operator= (String)aStack.pop();
                        //这里一定要注意了,千万不能漏,漏掉就有可能在括号的地方出错
                    }
                    else {  
                        if (Calculate.priority((String) expression.get(position))
                                <= Calculate.priority((String) aStack.top())&& aStack.top != -1)
                        {  
                            if (!((String) aStack.top()).equals("("))
                                //这个条件很重要,看到很多网上面都没有,结果求:(5*8-(6-3))*5   就会出错
                                //这个条件很重要,看到很多网上面都没有,结果求:(5*8-(6-3))*5   就会出错
                                //这个条件很重要,看到很多网上面都没有,结果求:(5*8-(6-3))*5   就会出错
                            {  
                            operator = (String) aStack.pop();  
                            right.add(operator);
                            }
                            
                        }  
                        aStack.push(expression.get(position));  
                           }  
                }  
            }
            else  
                right.add(expression.get(position));  
            position++;  
            if (position >= expression.size())  
                break;  
        }  
        while (aStack.top != -1) {  
            operator = (String) aStack.pop();  
            right.add(operator);  
        }  
    }  
  
    // 对右序表达式进行求值   (5*8-(6-3))*5

    private void getResult()
    {  
        this.toRight();  
        Stacks aStack = new Stacks();  
        String op1, op2, is = null;  
        Iterator it = right.iterator();  
      
        while (it.hasNext())
        {  
            is = (String) it.next();  
            if (Calculate.isOperator(is))
            {  
             //开始的时候没太在意这里,算三角函数一直出错,后来检查多次,终于找到这,不容易出错的让我忽略了  
            
                /*
                   这里是以前没改过的,超低级错误
                  op1 = (String) aStack.pop();
                  if(is.equals("S")||is.equals("C")||is.equals("T")||is.equals("L")){
                    aStack.push(Calculate.oneResult(is, op1));
                }
                   op2 = (String) aStack.pop();
                if(is.equals("+")||is.equals("-")||is.equals("*")||is.equals("/")){
                   aStack.push(Calculate.twoResult(is, op1, op2));
                }  
              */  
                if(is.equals("S")||is.equals("C")||is.equals("T")||is.equals("L")){
                    op1 = (String) aStack.pop();
                    aStack.push(Calculate.oneResult(is, op1));
                }
                
                if(is.equals("+")||is.equals("-")||is.equals("*")||is.equals("/")){
                    op1 = (String) aStack.pop();
                    op2 = (String) aStack.pop();
                    aStack.push(Calculate.twoResult(is, op1, op2));
                }  
            }
            else  
                aStack.push(is);  
        }  
        result = (String) aStack.pop();  
        it = expression.iterator();  
        while (it.hasNext())
        {  
            System.out.print((String) it.next());  
        }  
        System.out.println("=" + result);
        return ;
    }  
  
    public static void main(String[] args)
    {
        try {  
            System.out.println("Input a expression:");  
            BufferedReader is = new BufferedReader(new InputStreamReader(System.in));  
            for (;;)
            {  
                String input = new String();  
                input = is.readLine().trim();  
                if (input.equals("q"))  
                    break;  
                else
                {  
                    Expression boya = new Expression(input);  
                    boya.getResult();  
                }  
                System.out.println("Input another expression or input 'q' to quit:");  
            }  
            is.close();  
        }
        catch (IOException e)
        {  
            System.out.println("Wrong input!!!");  
        }  
      
    }
}

package expression;
import javax.swing.JOptionPane;


public class Calculate {
     // 判断是否为操作符号  
    public static boolean isOperator(String operator) {  
        if (operator.equals("+") || operator.equals("-")  
                || operator.equals("*") || operator.equals("/")  
                || operator.equals("(") || operator.equals(")")
                || operator.equals("T") || operator.equals("S")
                || operator.equals("C") || operator.equals("L"))  
            return true;  
        else  
            return false;  
    }  
  
    // 设置操作符号的优先级别
    //这里要记住,操作数越少,优先级就越高,一点小心得,给大家分享一下吧
    //还有,这里的“)”优先级是最低的,虽然没写明,但是能看的出来
   public static int priority(String operator)
    {  
        if (operator.equals("+") || operator.equals("-")  
                || operator.equals("("))  
            return 1;  
        else if (operator.equals("*") || operator.equals("/"))  
            return 2;  
        else if (operator.equals("S") || operator.equals("C")||operator.equals("T") || operator.equals("L"))  
            return 3;
        else
            return 0;  
    }  
  
    // 有两个操作数的函数运算  
    public static String twoResult(String operator, String a, String b) {  
        try {  
            String op = operator;  
            String rs = new String();  
            double x = Double.parseDouble(b);  
            double y = Double.parseDouble(a);  
            double z = 0;  
            if (op.equals("+"))  
                z = x + y;  
            else if (op.equals("-"))  
                z = x - y;  
            else if (op.equals("*"))  
                z = x * y;  
            else if (op.equals("/"))  
                z = x / y;  
            else  
                z = 0;  
            return rs + z;  
        } catch (NumberFormatException e) {  
            JOptionPane.showMessageDialog( null, "input has something wrong!","错误提示",JOptionPane.WARNING_MESSAGE);  
            return "Error";  
        }  
    }
    // 有一个操作数的函数运算
    public static String oneResult(String operator, String a) {  
        try {  
            String op = operator;  
            String rs = new String();  
            double x = Double.parseDouble(a);
            double z = 0;  
            if (op.equals("S"))  
                z = Math.sin(x);
            else if (op.equals("C"))  
                z = Math.cos(x) ;  
            else if (op.equals("T"))  
                z =Math.tan(x) ;  
            else if (op.equals("L"))  
                z = Math.log(x);  
            else  
                z = 0;  
            return rs + z;  
        } catch (NumberFormatException e) {  
            JOptionPane.showMessageDialog( null, "input has something wrong!","错误提示",JOptionPane.WARNING_MESSAGE);
              
            return "Error";  
        }  
    }

}
package expression;
import java.util.*;    
public class Stacks {
private LinkedList list=new LinkedList();    
   int top=-1;    
   public void push(Object value){    
      top++;    
      list.addFirst(value);    
   }    
   public Object pop(){    
      Object temp=list.getFirst();    
      top--;    
      list.removeFirst();    
      return temp;    
  
   }    
   public Object top(){    
   return list.getFirst();    
   }    
}