Você está na página 1de 3

import java.util.Scanner; import java.util.HashMap; import java.util.LinkedList; import java.util.

Stack; /** * This class demonstrate an implementation of the postfix * expression evaluator. * * The main method is a client of the class to evaluate postfix * expressions entered by users as a string using space as the * parser. * * Several collection classes from the Java standard library * has been used. * * Stack is the critical ADT to make the postfix evaluation * * LinkedList is used to collect parsed items from the input string. * This ADT is used between the methods of evaluate and tokenize. * * HashMap is used to collect pairs of operation string and the * corresponding operation enumerator item. This ADT makes the class * easier to expand if more operations are needed in the evaluation * process. * * Notice that this class does not have any exception handling protections. * * @author jxue * @version 0.2011-03-21 */ public class PostfixEvaluator { /** * This enum data structure is defined to encapsulate * conceptual operations from concrete symbol representations */ public enum Operation {ADD, SUB, MUL, DIV, POW}; /** * This HashMap ADT is defined to connect the * conceptual operations and the corresponding symbol representations */ public static HashMap<String, Operation> operators = new HashMap<String, Operation>(); static { operators.put("+", Operation.ADD); operators.put("-", Operation.SUB); operators.put("*", Operation.MUL); operators.put("/", Operation.DIV); operators.put("^", Operation.POW); } /** * operand stack, the core data structure in the algorithm */ private Stack<Integer> stack; /** * Constructor, only to initialze the stack */ public PostfixEvaluator(){ stack = new Stack<Integer>(); } /**

* Evaluate a postfix expression in String, return * the evaluated result in Integer * @param postfixExpression * @return */ public Integer evaluate(String postfixExpression){ // tokenize the string first LinkedList<Object> tokens = tokenize(postfixExpression); // process each item in the LinkedList for(Object item : tokens){ // separate the current item into two categories if (item instanceof Operation) { /** * for operators, pop the top two operands from the stack, * calculate the result of the single operation, and push * it to the top of the stack */ stack.push(operateSingle(stack.pop(), stack.pop( ), (Operation)item) ); } else { /** * for operands, push it to the stack */ stack.push((Integer)item); } /** * This line is for debugging purpose to demonstrate the intermediate status * of the operand stack */ System.out.println(stack+"\n\n"); } // the current top item in the stack should be the result return stack.pop(); } /** * This method takes the advantage of the HashMap ADT to separate * each String token into its corresponding type, then store the convert ed * token into a LinkedList ADT regardless of how many tokens there are, * and finally returns the resulting list. * @param input * @return */ private LinkedList<Object> tokenize(String input){ Scanner tokens = new Scanner(input); LinkedList<Object> list = new LinkedList<Object>(); String token; while (tokens.hasNext()){ token = tokens.next(); if (operators.containsKey(token)) { list.add(operators.get(token)); } else { list.add(Integer.valueOf(token)); } } return list; }

/** * This method simply carry calculation of a specific operation * @param op2 * @param op1 * @param operation * @return */ private Integer operateSingle(Integer op2, Integer op1, Operation operat ion) { switch(operation) { case ADD: return op1+op2; case SUB: return op1-op2; case MUL: return op1*op2; case DIV: return op1/op2; case POW: return (int)(Math.pow((double)op1, (double)op2)); } return null; } /** * The driver method for testing * @param args */ public static void main(String[] args){ String exp = ""; Scanner scan = new Scanner(System.in); PostfixEvaluator postfix = new PostfixEvaluator(); while(true){ System.out.println("Enter a postfix expression in intege r values"); System.out.println("Or type Q to exit"); exp = scan.nextLine(); if (exp.equals("Q")) break; System.out.println("Here is the result: " + postfix.eval uate(exp)); } System.out.println("So long..."); } }

Você também pode gostar