package suanfaTest;
import java.util.Stack;
public class biaodashiTest02 {
public String insetString(String expression){
String reslut = "";
for (int i = 0; i<expression.length(); i++){
if (expression.charAt(i) == '('||expression.charAt(i) == ')' ||
expression.charAt(i) == '*'||expression.charAt(i) == '/'||
expression.charAt(i) == '+'||expression.charAt(i) == '-'){
reslut += " "+expression.charAt(i)+" ";
}else {
reslut += expression.charAt(i);
}
}
return reslut;
}
public int operatorExpression(String expression){
Stack<Integer> numberStack = new Stack<Integer>();
Stack<Character> operatorStack = new Stack<Character>();
expression = insetString(expression);
String[] tokens = expression.split(" ");
for (String token:tokens){
if (token.length() == 0){
continue;
}else if (token.trim().charAt(0) == '+'||token.trim().charAt(0) == '-' ){
while (!operatorStack.isEmpty()&&(operatorStack.peek()=='+'||operatorStack.peek()=='-'||
operatorStack.peek()=='*'||operatorStack.peek()=='/')){
calculateExpression(numberStack,operatorStack);
}
operatorStack.push(token.charAt(0));
}else if (token.trim().charAt(0) == '*'||token.trim().charAt(0) == '/' ){
while (!operatorStack.isEmpty()&&(operatorStack.peek()=='*'||operatorStack.peek()=='/')){
calculateExpression(numberStack,operatorStack);
}
operatorStack.push(token.charAt(0));
}else if (token.trim().charAt(0) == '('){
operatorStack.push(token.charAt(0));
}else if (token.trim().charAt(0) == ')'){
while (operatorStack.peek()!='('){
calculateExpression(numberStack,operatorStack);
}
operatorStack.pop();//彈出'('
}else {
numberStack.push(Integer.parseInt(token.trim()));
}
}
while (!operatorStack.isEmpty()){
calculateExpression(numberStack,operatorStack);
}
int result = numberStack.peek();//這一步與numberStack.peek()作用相同
return result;
}
public void calculateExpression(Stack<Integer> numberStack,Stack<Character> operatorStack){
char op = operatorStack.pop();//運算符棧中彈出一個運算符
int op02 = numberStack.pop();//數字棧中彈出一個數字
int op01 = numberStack.pop();//數字棧中再彈出一個數字
if (op == '+'){
numberStack.push(op01+op02);
}else if (op == '-'){
numberStack.push(op01-op02);
}else if (op == '*'){
numberStack.push(op01*op02);
}else if (op == '/'){
numberStack.push(op01/op02);
}
}
public static void main(String args[]){
biaodashiTest02 bs = new biaodashiTest02();
String a = "1-(2*3+5)";
int result = bs.operatorExpression(a);
System.out.println(result);
}
}