import java.util.Scanner; /* Java application that evaluates FPAE's (fully-parenthesized arithmetic ** expressions) involving (only) integer operands. */ public class FPAE_Evaluator { private static final String LEFT_PAREN = "("; private static final String RIGHT_PAREN = ")"; private static final String PLUS = "+"; private static final String MINUS = "-"; private static final String TIMES = "*"; private static final String DIVIDE = "/"; private static final String ARITH_OPS = PLUS + MINUS + TIMES + DIVIDE; /* Prompts the user to enter an FPAE and, in response, displays its value. ** This repeats until the user enters the empty string. */ public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter FPAE: "); String s = keyboard.nextLine(); while (s.length() != 0) { System.out.println(evaluate(s)); System.out.print("\nEnter FPAE: "); s = keyboard.nextLine(); } System.out.println("Goodbye."); } /* Returns the result of evaluating the FPAE described by the given String. ** The syntax of FPAE's is described (recursively) by these rules: ** ** (1) An unsigned integer literal (e.g., "14", "3") is an FPAE ** (2) If A and B are FPAE's and op is one of "+", "-", "*", or "/", ** then ( A op B ) is an FPAE. ** ** It is assumed here that adjacent elements of an FPAE are separated by ** (one or more) spaces. For example, "( ( 13 - 4 ) * ( 7 + 12 ) )" will ** be evaluated correctly, but this method would fail if any of the spaces ** therein were absent. */ public static int evaluate(String fpae) { Scanner scanner = new Scanner(fpae); StackOfStrings stack = new StackOfStrings(fpae.length()); while (scanner.hasNext()) { String token = scanner.next(); // retrieve the next token if (token.equals(RIGHT_PAREN)) { String rightOperand = stack.topOf(); stack.pop(); String operator = stack.topOf(); stack.pop(); String leftOperand = stack.topOf(); stack.pop(); stack.pop(); // pop the left paren stack.push("" + applyOperator(leftOperand, operator, rightOperand)); } else { stack.push(token); } } return Integer.valueOf(stack.topOf()); } /* Carries out the arithmetic operation specified by the three parameters. */ private static int applyOperator(String left, String operator, String right) { int leftVal = Integer.valueOf(left); int rightVal = Integer.valueOf(right); if (operator.equals(PLUS)) { return leftVal + rightVal; } else if (operator.equals(MINUS)) { return leftVal - rightVal; } else if (operator.equals(TIMES)) { return leftVal * rightVal; } else if (operator.equals(DIVIDE)) { return leftVal / rightVal; } else { return 0; // What to do here? } } }