package com.stack;
public class Calculator {
public static void main(String[] args){
String expression = "5*6+10-100";
// 定义两个栈, 一个是数栈, 一个是操作符栈
ArrayStackCal numStack = new ArrayStackCal(10);
ArrayStackCal operStack = new ArrayStackCal(10);
// 定义需要的相关变量
int index = 0;
int num1 = 0;
int num2 = 0;
int oper = 0;
int res = 0;
char ch = ' ';
String chs = "";
while(true){
// 依次得到express中的每个字符
ch = expression.substring(index, index+1).charAt(0);
if(operStack.isOper(ch)){
if(!operStack.isEmpty()){
// 如果操作符栈不为空
// 和操作符栈中的操作符比较优先级
if(operStack.priority(ch) <= operStack.priority(operStack.peek())){
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
operStack.push(ch);
}else{
operStack.push(ch);
}
}else{
// 如果为空, 直接入栈
operStack.push(ch);
}
}else{
// 如果是数,直接入数栈
//numStack.push(ch-48); // 存入整数,而不是字符
chs += ch;
if(index == expression.length()-1){
numStack.push(Integer.parseInt(chs));
}else{
char temp = expression.substring(index+1, index+2).charAt(0);
if(numStack.isOper(temp)){
numStack.push(Integer.parseInt(chs));
chs = "";
}
}
}
index++;
if(index==expression.length()){
break;
}
}
operStack.listChar();
numStack.list();
while(!operStack.isEmpty()){
oper = operStack.pop();
num1 = numStack.pop();
num2 = numStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
}
res = numStack.pop();
System.out.println(expression+"="+res);
}
}
// 栈
class ArrayStackCal{
private int maxSize; //栈的大小
private int[] stack; // 数组模拟栈
private int top = -1;
public ArrayStackCal(int maxSize){
this.maxSize = maxSize;
stack = new int[maxSize];
}
// 判断栈满
public boolean isFull(){
return top == maxSize - 1;
}
// 判断栈空
public boolean isEmpty(){
return top == -1;
}
// 查看当前栈顶的值
public int peek(){
return stack[top];
}
// 入栈
public void push(int value){
// 先判断栈是否已满
if(isFull()){
System.out.println("栈已满");
return;
}
top++;
stack[top] = value;
}
// 出栈
public int pop(){
if(isEmpty()){
System.out.println("栈为空");
// 跑出异常
throw new RuntimeException("栈空,没有数据!");
}
int value = stack[top];
top--;
return value;
}
// 遍历栈
public void list(){
for(int i=top; i>-1;i--){
System.out.printf("stack[%d]=%d\n",i,stack[i]);
}
}
public void listChar(){
for(int i=top; i>-1;i--){
System.out.printf("stack[%d]=%c\n",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 res = 0;
switch(oper){
case '+':
res = num1 + num2;
break;
case '-':
res = num2 - num1;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num2/num1;
break;
}
return res;
}
}