Java Algorithms Parse postfix arithmetic expressions
import java.util.Stack; class ParsePost { private Stack<Integer> theStack = new Stack<>(); private String input; public ParsePost(String s) { input = s;//www. j a v a 2s . c om } public int doParse() { char ch; int j; int num1, num2, interAns; for (j = 0; j < input.length(); j++) // for each char, { ch = input.charAt(j); // read from input System.out.println(theStack); if (ch >= '0' && ch <= '9') // if it's a number theStack.push((int) (ch - '0')); // push it else // it's an operator { num2 = theStack.pop(); // pop operands num1 = theStack.pop(); switch (ch) // do arithmetic { case '+': interAns = num1 + num2; break; case '-': interAns = num1 - num2; break; case '*': interAns = num1 * num2; break; case '/': interAns = num1 / num2; break; default: interAns = 0; } // end switch theStack.push(interAns); // push result } } interAns = theStack.pop(); // get answer return interAns; } } public class Main { public static void main(String[] args) { int output; ParsePost aParser = new ParsePost("345+*612+/-"); output = aParser.doParse(); System.out.println("Evaluates to " + output); } }