Ai
2 Star 0 Fork 0

CS-IMIS-23/20172311hai

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
PostfixTester.java 3.09 KB
一键复制 编辑 原始数据 按行查看 历史
package week8;
import week2.EmptyCollectionException;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Stack;
/*
计算类的测试类
*/
public class PostfixTester {
public static void main(String[] args) throws EmptyCollectionException {
String infix, again;
int result;
Scanner in = new Scanner(System.in);
do {
PostfixEvaluator evaluator = new PostfixEvaluator();
System.out.println("Enter a valid in-fix expression one token " +
"at a time with a space between each token (e.g.5 4 + 3 2 1 - + *)");
System.out.println("Each token must be an integer or an operator(+,-,*,/)");
//输入中缀表达式
infix = in.nextLine();
//使用树将中缀表达式转换为后缀表达式
String suffix =toSuffix(infix);
//后缀表达式的计算结果
result = evaluator.evaluate(suffix);
System.out.println("\n后缀表达式为:" + suffix);
System.out.println("计算结果为:"+result);
System.out.println("The Expression Tree for that expression is:");
System.out.println(evaluator.getTree());
System.out.println("Evaluate another expression [Y/N]?");
again = in.nextLine();
System.out.println();
}
while (again.equalsIgnoreCase("Y"));
}
//用树实现中缀表达式转后缀表达式的静态方法
public static String toSuffix(String infix) {
String result = "";
String[] array = infix.split("\\s+");
Stack<LinkedBinaryTree> num = new Stack();
Stack<LinkedBinaryTree> op = new Stack();
for (int a = 0; a < array.length; a++) {
if (array[a].equals("+") || array[a].equals("-") || array[a].equals("*") || array[a].equals("/")) {
if (op.empty()) {
op.push(new LinkedBinaryTree<>(array[a]));
} else {
if ((op.peek().root.element).equals("+") || (op.peek().root.element).equals("-") && array[a].equals("*") || array[a].equals("/")) {
op.push(new LinkedBinaryTree(array[a]));
} else {
LinkedBinaryTree right = num.pop();
LinkedBinaryTree left = num.pop();
LinkedBinaryTree temp = new LinkedBinaryTree(op.pop().root.element, left, right);
num.push(temp);
op.push(new LinkedBinaryTree(array[a]));
}
}
} else {
num.push(new LinkedBinaryTree<>(array[a]));
}
}
while (!op.empty()) {
LinkedBinaryTree right = num.pop();
LinkedBinaryTree left = num.pop();
LinkedBinaryTree temp = new LinkedBinaryTree(op.pop().root.element, left, right);
num.push(temp);
}
Iterator itr=num.pop().iteratorPostOrder();
while (itr.hasNext()){
result+=itr.next()+" ";
}
return result;
}
}
Loading...
马建仓 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

搜索帮助