使用栈完成计算一个表达式的思路
*设置两个栈,一个栈存入数字栈numStack,一个栈存入符号栈operStack
1.通过一个index值作为指针用来遍历表达式
2.数字直接存入数字栈numStack中
3.如果为符号则进行判断
#符号栈为空,则直接存入
#不为空则与前一个运算符进行运算优先级比较
#若小于或等于,则从数字栈中取出两个数,符号栈中取出一个运算符,进行运算
#然后结果存入数字栈,扫描操作符存入符号栈
#若大于操作符优先级,则直接存入
4.扫描完成后,进行逐个取出运算
5.最后数字栈中只会存有一个数字,就是计算式结果
代码实现
package 栈;
import java.util.Stack;
public class 栈实现计算器 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack numStack = new Stack();
Stack operStack = new Stack();
String tipe = "3+2*6-5+9";
int index = 0;
int num1 = 0;
int num2 = 0;
while(index < tipe.length()){
char o = tipe.charAt(index);
index++;
if( isOper(o) == true ){
if(operStack.size() == 0){
operStack.add(o);
}else if(changeTo(o) == 0){
num1 = (int) (numStack.pop());
num2 = (int) (numStack.pop());
char op = (char) operStack.pop();
numStack.add(math(num1, num2, op));
operStack.add(o);
} else if(changeTo(o) == 1){
operStack.add(o);
}
} else {
numStack.add(o - 48);
}
}
while(true){
if(operStack.isEmpty()){
break;
}
num1 = (int) (numStack.pop());
num2 = (int) (numStack.pop());
char op = (char) operStack.pop();
numStack.add(math(num1, num2, op));
}
System.out.println(numStack.pop());
}
public static int changeTo(char oper){
if(oper == '*' || oper == '/'){
return 1;
} else if(oper == '+' || oper == '-'){
return 0;
} else {
return -1;
}
}
public static boolean isOper(char oper){
return oper == '+' || oper == '-' || oper == '*' || oper == '/';
}
public static int math(int num1, int num2, char oper){
int end = 0;
switch (oper) {
case '+':
end = num1 + num2;
break;
case '-':
end = num2 - num1;
break;
case '*':
end = num1 * num2;
break;
case '/':
end = num2 / num1;
break;
default:
break;
}
return end;
}
}