代码拉取完成,页面将自动刷新
package week8;
import java.util.Scanner;
import java.util.Stack;
/*
计算类说明
*/
public class PostfixEvaluator {
private String expression;
private Stack<ExpressionTree> treeStack;// 栈
//Sets up this evalutor by creating a new stack.
public PostfixEvaluator() {
treeStack = new Stack<ExpressionTree>();
}
//Retrieves and returns the next operand off of this tree stack.
private ExpressionTree getOperand(Stack<ExpressionTree> treeStack) {
ExpressionTree temp;
temp = treeStack.pop();
return temp;
}
//Evaluates the specified postfix expression by building and evaluating an expression tree.
public int evaluate(String expression) {
ExpressionTree operand1, operand2;//两个计算需要使用的操作数
char operator;
String tempToken;
Scanner parser = new Scanner(expression);
while (parser.hasNext()) {
tempToken = parser.next();
operator = tempToken.charAt(0);
if ((operator == '+') || (operator == '-') || (operator == '*')
|| (operator == '/')) {
operand1 = getOperand(treeStack);
operand2 = getOperand(treeStack);
//如果是操作符就进行计算
treeStack.push(new ExpressionTree(new ExpressionTreeOp(1, operator, 0), operand2, operand1));
} else {
treeStack.push(new ExpressionTree(new ExpressionTreeOp(2, ' ', Integer.parseInt(tempToken)), null, null));
}
}
return (treeStack.peek()).evaluateTree();
}
// /Returns the expression tree associated with this postfix evaluator.
public String getTree() {
return (treeStack.peek()).printTree();
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。