/**
* 数组模拟栈-简易计算器
*/
public class ArrayStackDemo {
public void calculate(String s){
//数字栈
ArrayStack numStack = new ArrayStack(10);
//符号栈
ArrayStack operStack = new ArrayStack(10);
int index = 0;
char c;
int res = 0;
int num1 = 0;
int num2 = 0;
String num = "";
do {
c = s.substring(index, index + 1).charAt(0);
//是符号
if (isOper(c)) {
if (operStack.isEmpty()) {
operStack.push(c);
} else { //符号栈不为空,如果栈中的优先级大就取数字栈的2个进行运算
if (priority(c) <= priority(operStack.peek())) {
num2 = numStack.pop();
num1 = numStack.pop();
res = cal(num1, num2, operStack.pop());
numStack.push(res);
operStack.push(c);
} else {
operStack.push(c);
}
}
} else {
num = num + c;
if (index == s.length()-1){
numStack.push(Integer.parseInt(num));
}else if (isOper(s.substring(index+1, index+2).charAt(0))){
numStack.push(Integer.parseInt(num));
num = "";
}
}
System.out.print(c);
index++;
} while (index < s.length());
while (true){
if (!operStack.isEmpty()){
num2 = numStack.pop();
num1 = numStack.pop();
res = cal(num1, num2, operStack.pop());
numStack.push(res);
}else {
break;
}
}
res = numStack.pop();
System.out.println("="+res);
}
// * / + - 运算符优先级
private int priority(int oper){
if (oper=='*'||oper=='/'){
return 1;
}
if (oper=='+'||oper=='-'){
return 0;
} else {
return -1;
}
}
// 判断是不是* / + -
private boolean isOper(int val){
return val=='+'||val=='-'||val=='*'||val=='/';
}
private static int cal(int num1, int num2, int oper){
int res = 0;
switch (oper){
case '+':
res = num1 + num2;
break;
case '-':
res = num1 - num2;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num1 / num2;
break;
default:
break;
}
return res;
}
public static void main(String[] args){
// ArrayStack stack = new ArrayStack(3);
// stack.push(1);
// stack.push(2);
// stack.push(3);
// stack.push(4);
// stack.list();
// stack.pop();
// stack.list();
// stack.pop();
// stack.pop();
// stack.pop();
new ArrayStackDemo().calculate("11+1*1");
new ArrayStackDemo().calculate("10+11-1");
new ArrayStackDemo().calculate("10+10/10");
new ArrayStackDemo().calculate("10+10+10");
}
}
class ArrayStack{
private int maxsize;
private int[] stack;
private int top = -1;
public ArrayStack(int maxsize) {
this.maxsize = maxsize;
stack = new int[maxsize];
}
//栈满
public boolean isFull(){
return top == maxsize-1;
}
//栈空
public boolean isEmpty(){
return top == -1;
}
//入栈
public void push(int i){
if (isFull()){
System.out.println("栈满~");
return;
}
top++;
stack[top] = i;
}
//出栈
public int pop(){
if (isEmpty()){
System.out.println("栈空~");
return -1;
}
int i = stack[top];
top--;
return i;
}
public int peek(){
if (isEmpty()){
System.out.println("栈空~");
return -1;
}
return stack[top];
}
public void list(){
if (isEmpty()){
System.out.println("栈空~");
return;
}
for (int i = top; i >= 0; i--) {
System.out.print("stack["+i+"]="+stack[i]+" ");
}
System.out.println();
}
}