package com.nps.base.xue.DataStructure.stack.utils; import java.util.Scanner;
import java.util.Stack; /*
* @author XueWeiWei
* @date 2019/7/7 9:02
*/
public class PostfixEvaluator {
private final static char ADD = '+';
private final static char SUBTRACT = '-';
private final static char MULTIPLY = '*';
private final static char DIVIDE = '/'; private Stack<Integer> stack; /**
* 创建一个 evaluator
*/ public PostfixEvaluator() {
stack = new Stack<Integer>();
} public int evaluate(String expr){
int op1,op2, result=0;
String token;
Scanner parser = new Scanner(expr); while (parser.hasNext()){
token = parser.next(); if (isOperator(token)){
op2 = (stack.pop()).intValue();
op1 = (stack.pop()).intValue();
result = evaluateSingleOperator(token.charAt(0),op1,op2);
stack.push(new Integer(result));
}else {
stack.push(new Integer(Integer.parseInt(token)));
}
}
return result;
} private boolean isOperator(String token){
return (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/"));
} private int evaluateSingleOperator(char operator, int op1 , int op2){
int result = 0; switch (operator){
case ADD:
result = op1 + op2;
break;
case SUBTRACT:
result = op1- op2;
break;
case MULTIPLY:
result = op1 * op2;
break;
case DIVIDE:
result = op1 / op2;
break;
} return result;
}
}
package com.nps.base.xue.DataStructure.stack.test; import com.nps.base.xue.DataStructure.stack.utils.PostfixEvaluator; import java.util.Scanner; /*
* @author XueWeiWei
* @date 2019/7/7 9:01
*/
public class PostfixTester {
public static void main(String[] args) {
String expression,again;
int result; Scanner in = new Scanner(System.in); do {
PostfixEvaluator evaluator = new PostfixEvaluator();
System.out.println("e.g. 5 4 + 3 2 1 - + *");
System.out.println();
expression = in.nextLine(); System.out.println("输入的表达式:" + expression);
result = evaluator.evaluate(expression);
System.out.println(">>>>>结果: " + result); System.out.println("是否输入下一个表达式?[Y/N]");
again = in.nextLine(); }while (again.equalsIgnoreCase("y"));
}
}