1.举例说明:8-3*2+5*(9-3)/2;
计算上面所说的这个例子,在运算过程中不仅要注意运算的顺序,运算符的优先级等等;在这个简单的算数式子当中,“()”的优先级最高,“*”和“/”的优先级次之,“+,-”的优先级最低。由此在计算的过程当中就必须依照优先级的高低来进行计算。
2.波兰式和逆波兰式(中缀表达式&后缀表达式)
波兰式转逆波兰式(中缀表达式转后缀表达式):
![](https://img-blog.csdnimg.cn/20210912081152977.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5Zyo54Ku54Gr5Lit5YmN6L-b,size_20,color_FFFFFF,t_70,g_se,x_16)
后缀表达式计算最终结果:
![](https://img-blog.csdnimg.cn/20210912082816600.png?x-oss-process=image/watermark,type_ZHJvaWRzYW5zZmFsbGJhY2s,shadow_50,text_Q1NETiBA5Zyo54Ku54Gr5Lit5YmN6L-b,size_20,color_FFFFFF,t_70,g_se,x_16)
public class Operator {
//操作符名称,比如:+-*/()
public String symbol;
/**
* 构造方法,传入符号入参
* @param symbol
*/
public Operator(String symbol){
this.symbol = symbol;
}
/**
* 判断表达式是否是以操作符开头
* @param expression
* @return
*/
public static boolean isStartWithOperator(String expression){
return expression.startsWith("+") ||
expression.startsWith("-") ||
expression.startsWith("*") ||
expression.startsWith("/") ||
expression.startsWith("(") ||
expression.startsWith(")");
}
/**
* 返回该符号的优先级
* @return
*/
public int getPriority(){
switch (symbol){
case "+": return 1;
case "-": return 1;
case "*": return 2;
case "/": return 2;
case "(": return 3;