A Postfix Calculator implemented using a Stack in Java:

/* Sample input
Spaces are important:
	"65 3 5 * + 83 -" = (65 + (5 * 3)) - 83 = -3
*/
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) {
//Process the list into an ArrayList
		List<String> processedList = new ArrayList<String>();
		if (!input.isEmpty()) {
			StringTokenizer st = new StringTokenizer(input);
			while (st.hasMoreTokens()) {
				processedList.add(st.nextToken());
			}
		} else {
			return "Error";
		}
//A Stack, we will use this for the calculation
		Stack<String> tempList = new Stack<String>();
//Iterate over the whole processed list
		Iterator<String> iter = processedList.iterator();
		while (iter.hasNext()) {
			String temp = iter.next();
			if (temp.matches("[0-9]*")) {
//If the current item is a number (aka operand), push it onto the stack
				tempList.push(temp);
			} else if (temp.matches("[*-/+]")) {
//If the current item is an operator we pop off the last two elements 
//of our stack and calculate them using the operator we are looking at. 
//Push the result onto the stack. 
				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 the last element on the Stack.
		return tempList.pop();
	}
}

4 thoughts on “Java – Postfix Calculator

  1. Hi Kevin,

    i’m Nico Krebs, Chief Software Architect at Projektmotor GmbH Leipzig. I am researching in Software Engineering processes and am lecturing about how to build applications which are highly extensible and fault tolerant.

    i have created a git repository with a JAVA (NetBeans) project which uses your code in the CalculatorGUI method including a link to your post on your blog. (-> https://github.com/nkoding/SeminarSampleCode/blob/master/CleanCode_Calculator/src/cleancode/calculator/CalculatorGUI.java )

    I do not plan to build a commercial application based on your code.

    Instead i will improve this basic snippet until it has the properties mentioned above. I will tag the code history according to the chapters of my seminars and talks to demonstrate how to build professional error correcting modular applications.

    Would you allow me to use your code as an example during my lectures, seminars and talks and in the git repo?

    best regards,
    Nico

  2. Hi Mr.Kevin

    when I run the code, it shows to me this error

    “Error: Main method not found in class helloWorld.PostFixCompute, please define the main method as:
    public static void main(String[] args)
    or a JavaFX application class must extend javafx.application.Application”

    What I have to do to run the code ?

    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *