主方法代码
public static void main(String[] args) {
Idea02 equation=new Idea02();
Scanner in=new Scanner(System.in);
String ReversePolish = equation.toReversePolish(in.next());//扫描输入的表达式,转为后缀表达式
//6 10 3 40.2 + 8 + - 5 * - 8 +
String[] expression = ReversePolish.split(" ");//对表达式之间每个数字之间插入空格值
Stack<Double> stack = new Stack<>();//初始化一个栈
for (int i = 0; i < expression.length; i++) {//循环初始化出表达式的长度计算
switch (expression[i]) {
//从左至右对后缀表达式进行扫描,将扫描出来的数字压入堆栈,
//遇到运算符,弹出栈顶元素和次顶元素,
case "+" : {
double num1 = stack.pop();
double num2 = stack.pop();
double result = num1+num2;
stack.push(result);//弹出结果入栈
break;
}
case "-" : {
double num1 = stack.pop();
double num2 = stack.pop();
double result = num2-num1;//这里一定注意,运算是次顶元素在前,栈顶元素在后,避免减法和除法求反
stack.push(result);
break;
}
case "*" : {
double num1 = stack.pop();
double num2 = stack.pop();
double result = num1*num2;
stack.push(result);
break;
}
case "/" : {
double num1 = stack.pop();
double num2 = stack.pop();
double result = num2/num1;//这里一定注意,运算是次顶元素在前,栈顶元素在后,避免减法和除法求反
stack.push(result);
break;
}
default: {
Double ing = Double.parseDouble(expression[i]);//将字符串转化为双精度浮点型
stack.push(ing);//栈中最后一个数字即为最后的结果
}
}
}
System.out.println(stack.pop());//输出结果
}
改后缀表达式代码
public class Idea02 {
public static String toReversePolish(String expression) {//定义中缀表达式
Stack<String> stack1 = new Stack<>();//初始化存数字的栈1
Stack<String> stack2 = new Stack<>();//初始化存运算符的栈2
String number = "";//定义要计算的数字
for (int i = 0; i < expression.length();) {//从左到右开始扫描中缀表达式
boolean isAll = false;//定义是否以及扫描完毕
while((expression.charAt(i)>='0' && expression.charAt(i) <= '9') || expression.charAt(i)=='.') {//从左至右扫描中缀表达式; 遇到操作数时,将其压至栈1;
number += expression.charAt(i);//按顺序赋值
i++;
if (i == expression.length()) {
isAll = true;
break;
}
}//循环数字完毕
if (!number.isEmpty()) {//判断数字是否为空
stack2.push(new StringBuffer(number).reverse().toString());//生成后缀表达式
number = "";
}
if (isAll) {
break;
}
if (expression.charAt(i) == ')') {//当扫描到后括号时候
while (!stack1.peek().equals("(")) {//如果栈1的栈顶不为(
stack2.push(stack1.pop());//如果栈2为空,或栈顶运算符为左括号“(”,则直接将此运算符入栈;
}
stack1.pop();
i++;
continue;
}
while(!(expression.charAt(i)>='0' && expression.charAt(i) <= '9')) {
char symbol = expression.charAt(i);
if ((stack1.size() == 0) || (stack1.peek().equals("(")) || (symbol=='(')) {
stack1.push(symbol+"");
i++;
break;
}
if ((symbol == '+') || (symbol == '-')) {
stack2.push(stack1.pop());
continue;
} else {
if ((stack1.peek().equals("+")) || (stack1.peek().equals("-"))) {
stack1.push(symbol+"");
i++;
break;
}
if ((stack1.peek().equals("*")) || (stack1.peek().equals("/"))) {
stack2.push(stack1.pop());
continue; // 否则,若优先级比栈顶运算符的高,也将运算符压入栈1;
}
}
}
}
while(stack1.size() != 0) {
stack2.push(stack1.pop()); // 否则,将栈2顶的运算符弹出并压入到栈1中,再次循环与栈2中新的栈顶运算符相比较;
}
String s1 = "";
while(stack2.size() != 0) {
s1 += stack2.pop();
if (stack2.size() != 0) {
s1 += " ";
}
}
return new StringBuffer(s1).reverse().toString();//倒序生成后缀表达式
}
}