import java.util.Stack;
//計算中綴表達式
//1+2*(3-4)+5
public class Test1 {
/**
* 後綴表達式計算
* @param expstr
* @return
*/
public static String toPostfix(String expstr){
String postfix="";
Stack<String> stack = new Stack<String>();
int i=0;
int explength=expstr.length();//字符串的長度
while (i<explength) {
char ch = expstr.charAt(i);
switch (ch) {
case '+':
case '-':
while (!stack.empty()&&!stack.peek().equals("(")) {
postfix+=stack.pop();
//如果棧非空,並且棧的棧頂不是“左括號”,也就是棧頂優先級>=該操作符的優先級出棧,添加到後綴表達式中
}
stack.push(ch+"");//將該操作符入棧
i++;
break;
case '*':
case '/':
while (!stack.empty()&&(stack.peek().equals("*")||stack.peek().equals("/"))) {
postfix+=stack.pop();
}
stack.push(ch+"");
i++;
break;
case '(':
stack.push("(");//左括號直接入棧
i++;
break;
case ')':
String out = stack.pop();//右括號出棧
while (out!=null&&!out.equals("(")) {
//如果出的不是null,並且不是左括號
postfix+=out;//添加到後綴表達式
out=stack.pop();
}
i++;
break;
default:
while (i<explength&&ch>='0'&&ch<='9') {
postfix+=ch;
i++;
if (i<explength) {
ch=expstr.charAt(i);
}
}
postfix+=" "; //以空格爲分隔符
}
}
while (!stack.empty()) {
postfix+=stack.pop();
}
return postfix;
}
//計算後綴表達式
public static int value(String postfix){
int result=0;
int len = postfix.length();
Stack<Integer> stack = new Stack<Integer>();
int i=0;
while (i<len) {
char ch = postfix.charAt(i);
if (ch>='0'&&ch<='9') {
result = 0;
while (ch!=' ') {//上面的後綴表達式以空格爲分隔符
result = result*10+Integer.parseInt(ch+"");
//如果不是空格的話,就計算該數。比如 123 456 +。
i++;
ch=postfix.charAt(i);
}//
i++;
stack.push(result);//將操作數壓棧
}else{
int y = stack.pop().intValue();
int x = stack.pop().intValue();
switch (ch) {
case '+':
result = x+y ;
break;
case '-':
result = x-y ;
break;
case '*':
result = x*y ;
break;
case '/':
result = x/y ;
break;
}
stack.push(new Integer(result));
i++;
}
}
return stack.pop().intValue();
}
}