2 Star 0 Fork 0

CS-IMIS-23/20172311hai

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
PostfixEvaluator.java 1.75 KB
一键复制 编辑 原始数据 按行查看 历史
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();
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/CS-IMIS-23/20172311hai.git
git@gitee.com:CS-IMIS-23/20172311hai.git
CS-IMIS-23
20172311hai
20172311hai
master

搜索帮助