用栈实现简易计算器
理解:就是运算的顺序,如同自己计算时,碰到优先级先进行运算,最后省下来的都是同一个优先级的,最后再集体运算,而栈实现了回溯的功能,能够找上一个的元素
使用了中缀表达式,加入括号使用后缀表达式。
package stack;
import java.util.Optional;
public class Calculator {
public static void main(String[] args) {
String expression = "300+2*6-1";
CalStack numStack = new CalStack(10);
CalStack operStack = new CalStack(10);
int index = 0;
int num1 = 0;
int num2 = 0;
int oper = 0;
int res = 0;
char ch = ' ';
String keyNum = "";
while (true){
ch = expression.substring(index,index+1).charAt(0);
if(operStack.isOper(ch)){
if(!operStack.isEmpty()){
if(operStack.prioroty(ch) <= operStack.prioroty(operStack.getlast())){
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 {
if(index == expression.length() -1 ) {
numStack.push(ch - 48);
}else {
keyNum += ch;
if (operStack.isOper(expression.substring(index + 1).charAt(0))) {
numStack.push(Integer.parseInt(keyNum));
keyNum = "";
}
}
}
index++ ;
if(index >= expression.length()){
break;
}
}
while(true) {
if(operStack.isEmpty()){
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1,num2,oper);
numStack.push(res);
}
System.out.printf("表达式%s = %d",expression,numStack.pop());
}
}
class CalStack{
private int maxSize;
private int[] stack;
private int top;
public CalStack(int maxSize) {
this.maxSize = maxSize;
this.stack = new int[maxSize];
top = -1;
}
public boolean isFull(){
return top >= maxSize -1;
}
public boolean isEmpty(){
return top == -1;
}
public void push(int data){
if(isFull()) {
System.out.println("栈满了");
return;
}
top++;
stack[top] = data;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈空");
}
int value = stack[top];
top--;
return value;
}
public void showStack(){
for(int i = 0; i <= top; i++) {
System.out.printf("%d\t",stack[i]);
}
}
public int getlast(){
if(isEmpty()){
throw new RuntimeException("栈空");
}
return stack[top];
}
public int prioroty(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 / num2;
break;
default:
throw new RuntimeException("错了");
}
return res;
}
}