Using stack to calculate suffix expression

Posted Jun 7, 20201 min read

public class PolandExpressionDemo {
/* Calculate the result of inverse Polish expression(suffix expression)
Assuming that each number or character is separated by a space
4 * 5-8 + 60 + 8/2 = 4 5 * 8-60 + 8 2/+
/
public double calculatePoland(String exp) {
String[]strings = exp.split(" ");
Stack stack = new Stack<>();
for(String s:strings) {
double n1, n2;
switch(s) {
case "
":
n1 = stack.pop();
n2 = stack.pop();
stack.push(n1 * n2);
break;
case "/":
n1 = stack.pop();
n2 = stack.pop();
stack.push(n2/n1);
break;
case "+":
n1 = stack.pop();
n2 = stack.pop();
stack.push(n1 + n2);
break;
case "-":
n1 = stack.pop();
n2 = stack.pop();
stack.push(n2-n1);
break;
default:
stack.push(Double.parseDouble(s));
break;
}
}
return stack.pop();
}

    public static void main(String[]args) {
        PolandExpressionDemo app = new PolandExpressionDemo();
        System.out.println(app.calculatePoland("4 5 * 8-60 + 8 2/+"));
    }
}