Ask Question

Name:
Title:
Your Question:

Answer Question

Name:
Your Answer:
User Submitted Source Code!


Description:
  PostFixCompute.java
Language: JAVA
Code:
import java.util.Iterator;
import java.util.Stack;
import java.util.StringTokenizer;
import java.util.List;
import java.util.ArrayList;
 
public class PostFixCompute {
    public static String compute(String input) {
        List<String> processedList = new ArrayList<String>();
        if (!input.isEmpty()) {
            StringTokenizer st = new StringTokenizer(input);
            while (st.hasMoreTokens()) {
                processedList.add(st.nextToken());
            }
        } else {
            return "Error";
        }
        Stack<String> tempList = new Stack<String>();
        Iterator<String> iter = processedList.iterator();
        while (iter.hasNext()) {
            String temp = iter.next();
            if (temp.matches("[0-9]*")) {
                tempList.push(temp);
            } else if (temp.matches("[*-/+]")) {

                if (temp.equals("*")) {
                    int rs = Integer.parseInt(tempList.pop());
                    int ls = Integer.parseInt(tempList.pop());
                    int result = ls * rs;
                    tempList.push("" + result);
                } else if (temp.equals("-")) {
                    int rs = Integer.parseInt(tempList.pop());
                    int ls = Integer.parseInt(tempList.pop());
                    int result = ls - rs;
                    tempList.push("" + result);
                } else if (temp.equals("/")) {
                    int rs = Integer.parseInt(tempList.pop());
                    int ls = Integer.parseInt(tempList.pop());
                    int result = ls / rs;
                    tempList.push("" + result);
                } else if (temp.equals("+")) {
                    int rs = Integer.parseInt(tempList.pop());
                    int ls = Integer.parseInt(tempList.pop());
                    int result = ls + rs;
                    tempList.push("" + result);
                }
            } else {
                return "Error";
            }
        }
        return tempList.pop();
    }
}
Comments: