将带有计算的优先级和括号的中序表达式变成符合某文法的后序表达式。
- 《编程导论(Java)·5.5.2》的参考资料
- 解释器模式中或许需要的工具
直接上代码。
package intent.interpreter.calculator2;
import java.util.HashMap;
import java.util.Stack;
import tool.God;
public class Nothing{
private static HashMap<Character,Integer> priority=new HashMap<Character,Integer>(){
{
put('+', 1);
put('-', 1);
put('/', 2);
put('*', 2);
put('(', 0);
}
};
/**
* 将带有计算的优先级和括号的中序表达式inOrder变成符合前述文法的后序表达式
*/
static String inToPost(String inOrder) {
Stack<Character> s = new Stack<>();
String res = "";//postfix expression
char temp ;//保存s.pop()
char[] expr = inOrder.trim().toCharArray();
for (char x :expr) {
//如果是操作数,直接输出
if ( !isOperator(x) && ( x!='(' ) && ( x!=')') ) {
res = res + x;
}else if (x=='(') {
s.push(x);//入栈
}else if (x==')') {//输出栈中的右操作符直到取出(。
temp = s.pop();
while (temp!='(') {
res = res + temp;
temp = s.pop();
}
temp = '\0';
}else if (isOperator(x)) {//与栈顶操作符比较优先级
if (!s.isEmpty()) {
temp = s.pop();
int prio1 = priority.get(temp);
int prio2 = priority.get(x);
while ( prio1 >= prio2 ) {
res = res + temp;
prio1 = -1;
if (!s.isEmpty()) {
temp = s.pop();
prio1 = priority.get(temp);
}
}
if ((prio1 < prio2) && (prio1 != -1)){
s.push(temp);
}
}
s.push(x);
}
}// end for
while (!s.isEmpty() ) {
temp = s.pop();
res = res + temp;
}
return res;
}
static boolean isOperator(char c) {
return c=='+'||c=='-'||c=='*'||c=='/';
}
static void test(){
String inOrder = "a+b*c-d";
inOrder= (String)God.getValue("expression");
System.out.println(" inOrder = "+inOrder);
System.out.println(" postOrder = "+inToPost(inOrder));
}
}
inOrder = a+b*c-d
postOrder = abc*+d-
inOrder = (a+b)*(c-d)
postOrder = ab+cd-*
inOrder = a+b/c*(c-d)
postOrder = abc/cd-*+
使用配置文件时:
#intent.interpreter.calculator2. Alph ={a|b|c|d}.Op={*|+|-}
#expression = (a+b)*(c-d)
#expression =a+b*c-d
expression = a+b/c*(c-d)