例如: (3+4)X5-6对应的后缀表达式就是3 4 + 5 X 6-,针对后缀表达式求值步骤如下:
// 1.从左至右扫描,将3和4压入堆栈;
// 2.遇到+运算符,因此弹出4和3 (4 为栈顶元素,3为次顶元素),计算出3+4的值,得7,再将7入栈;
// 3.将5入栈;
// 4.接下来是X运算符,因此弹出5和7,计算出7X5=35,将35入栈;
// 5.将6入栈;
// 6.最后是-运算符,计算出35-6的值,即29,由此得出最终结果
import java.util.Stack;
public class LatterException {
public static void main(String[] args) {
// char ch[]={'0','1','2'};
// System.out.println(new String(ch,0,1));
LatterException latterException = new LatterException();
System.out.println(latterException.cal1("3 4 + 5 * 6 -"));
}
public double cal1(String exception){
String[] arr = exception.split(" ");
print(arr);
System.out.println(arr);
// 1、创建存放数字的栈
Stack<Double> doubleStack = new Stack<>();
int pos=0,len=arr.length;
while(pos<len){
if(isOperator(arr[pos])){
double num1=doubleStack.pop();
double num2=doubleStack.pop();
doubleStack.push(cal(arr[pos],num2,num1));
System.out.println(doubleStack);
}else{
doubleStack.push(Double.parseDouble(arr[pos]));
System.out.println(doubleStack);
}
pos++;
}
return doubleStack.pop();
}
public boolean isOperator(String oper){
//用String类的equals()方法,来判断而且形式为"+".equals(oper)以防止空对象的出现,如果用oper=="-",那么返回值一直是false
if("+".equals(oper)||"-".equals(oper)||"*".equals(oper)||"/".equals(oper)){
return true;
}
return false;
}
//计算函数
public double cal(String oper,double num1,double num2) {
return switch (oper) {
case "+" -> num1 + num2;
case "-" -> num1 - num2;
case "*" -> num1 * num2;
case "/" -> num1 / num2;
default -> throw new RuntimeException("运算符有错误");
};
}
public void print(String arr[]){
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
}
}