java的逆波蘭式演算法

來源:互聯網
上載者:User

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, "+-*/()", 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);   
                        }   
                    } else {   
                        if (Calculate.priority((String) expression   
                                .get(position)) <= Calculate   
                                .priority((String) aStack.top())   
                                && aStack.top != -1) {   
                            operator = (String) aStack.pop();   
                            if (!operator.equals("("))   
                                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);   
        }   
    }   
  
    // 對右序運算式進行求值   
    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();   
                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);   
    }   
  
    public static void main(String avg[]) {   
        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!!!");   
        }   
    }   
}   

 

java 代碼
package expression;   
  
public class Calculate {   
    // 判斷是否為操作符號   
    public static boolean isOperator(String operator) {   
        if (operator.equals("+") || operator.equals("-")   
                || operator.equals("*") || operator.equals("/")   
                || operator.equals("(") || operator.equals(")"))   
            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  
            return 0;   
    }   
  
    // 做2值之間的計算   
    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) {   
            System.out.println("input has something wrong!");   
            return "Error";   
        }   
    }   
}   

java 代碼
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();    
   }    
}    

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.