
public class Exercise20_14 {
public static void main(String[] args) {
System.out.print("Enter a postfix expression: ");
String expression = new Scanner(System.in).nextLine();
System.out.println("expression = " + format(evaluateExpression(expression)));
public static double evaluateExpression(String expression) {
Stack stack = new Stack<>();
String[] tokens = expression.split(" ");
Set set = new HashSet<>(Arrays.asList("+", "-", "*", "/", "^", "%"));
for (String op: tokens) {
stack.push(Double.parseDouble(op));
} catch (NumberFormatException ex) {
double op1 = stack.pop();
double op2 = stack.pop();
case "+": stack.push(op2 + op1); break;
case "-": stack.push(op2 - op1); break;
case "*": stack.push(op2 * op1); break;
case "/": stack.push(op2 / op1); break;
case "^": stack.push(Math.pow(op2, op1)); break;
case "%": stack.push(op2 % op1); break;
public static String format(double value) {
String v = String.valueOf(value);
return v.endsWith("0") ? String.valueOf((int)value) : v;

