import java.util.Scanner; import java.util.Stack; import java.util.regex.Pattern; /** * Postfix lab. * @author cs416 * @version 2 */ public class PostfixCalculator { private final Pattern integerPattern = Pattern.compile("-?\\d+"); /** * Evaluates the postfix expression and returns the answer as an int. * * This function throws an IllegalStateException for the following * conditions: * - an invalid operator is encountered * - There are too few operands on the stack to perform the operation * - trying to divide by zero * - There are too manu operands left on the stack after processing each * token of the expression (stack size != 1 after processing) * * @param expression The postfix expression to evaluate * @return int */ public int evaluate(String expression) { throw new UnsupportedOperationException("TO BE IMPLEMENTED"); } /** * Returns true if the token parameters matches the regex * for an integer. * @param token the token to validate * @return boolean */ private boolean isInteger(String token) { if (token == null || token.isEmpty()) { return false; } return integerPattern.matcher(token).matches(); } /** * If the token parameter is a valid operator return true, otherwise return false. * @param token The token to validate * @return boolean */ public boolean isValidOperator(String token) { throw new UnsupportedOperationException("TO BE IMPLEMENTED"); } /** * The main function. * @param args The commandline arguments. */ public static void main(String[] args) { PostfixCalculator pcalc = new PostfixCalculator(); System.out.println("Enter postfix expressions until EOF ( or Ctrl-D)"); Scanner s = new Scanner(System.in); while (s.hasNextLine()) { String exp = s.nextLine(); try { System.out.println(pcalc.evaluate(exp)); } catch (IllegalStateException e) { System.err.println(e); } } s.close(); } }