package 基础;
public class 栈计算器 {
public static void main(String[] args) {
String exp = "3+2*6-2";
//创建两个栈:数栈,符号栈;
Stack numStack = new Stack(10);
Stack operStack = new Stack(10);
//定义相关变量
int index= 0; //用于扫描
int num1 = 0;
int num2 = 0;
int oper = 0;
int re = 0;
char ch = ' ';
//循环扫描exp
while(true){
//依次得到exp每一个字符
ch = exp.substring(index,index+1).charAt(0);
//判断ch是什么做相应处理
if(operStack.isOper(ch)){
//判断当前符号栈是不是为空
if(!operStack.isNull()){
//有操作符号,比较优先级
if(operStack.priority(ch) <= operStack.priority(operStack.peek())){
//优先级小,开始运算
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
re = numStack.cal(num1, num2, oper);
numStack.push(re);
operStack.push(ch);
}else{
//当前操作符号优先级大
operStack.push(ch);
}
}else{
operStack.push(ch);
}
} else {
numStack.push(ch - 48);
}
index++;
if(index >= exp.length()){
break;
}
}
while(true){
//符号栈为空计算到最后的结果,栈中只有一个数字
if(operStack.isNull()){
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
re = numStack.cal(num1, num2, oper);
numStack.push(re);
operStack.push(ch);
}
System.out.printf("%s=%d",exp,numStack.pop());
}
}
//创建栈
class Stack{
private int maxSize;
private int[] stack; //数组模拟栈,数据放在数组中
private int top = -1; //指向栈顶,-1表示没有数据
public Stack(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
//返回当前栈顶
public int peek() {
return stack[top];
}
//满
public boolean isFull(){
return top == maxSize-1;
}
//空
public boolean isNull(){
return top== -1;
}
//入栈
public void push(int value){
if(isFull()){
return;
}top++;
stack[top] = value;
}
public int pop(){
if(isNull()){
throw new RuntimeException("没有数据");
}
int value = stack[top];
top--;
return value;
}
public void list(){
if(isNull()){
System.out.println("空");
}for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d",i,stack[i]);
}
}
//返回运算符优先级,程序员界定,优先级使用数字表示,数字越大优先级越高。
public int priority(int oper) {
if(oper == '*' || oper == '/'){
return 1;
}else if (oper == '+' || oper == '-') {
return 0;
}else {
return -1; //假定运算只有加减乘除
}
}
//判断是不是运算符
public boolean isOper(char val){
return val == '+' || val == '-' || val == '*' || val == '/';
}
//计算方法
public int cal(int num1,int num2,int oper){
int re = 0;
switch (oper) {
case '+':
re = num1+num2;
break;
case '-':
re = num2-num1; //注意减法顺序
break;
case '*':
re = num1*num2;
break;
case '/':
re = num1/num2;
break;
default:
break;
}
return re;
}
}
01-12
560
11-18
697