栈实现综合计算器 java 详细讲解
案例
解题思路
代码实现
package com.qf.stack;
public class Caculator {
public static void main(String[] args) {
StackArray numArray=new StackArray(20);
StackArray operateArray=new StackArray(20);
int index=0;
int num1=0;
int num2=0;
int res=0;
String funNum="";
String expression="7*2*2-5+1-5+3-4";
for (int i = 0; i < expression.length(); i++) {
char ch=expression.subSequence(i,i+1).charAt(0);
if (StackArray.isOperate(ch)){
if (operateArray.isEmpty()){
operateArray.push(ch);
}else{
int peek = operateArray.peek();
int local = operateArray.priority((char) peek);
int chars = operateArray.priority(ch);
if (local>=chars){
num1 = numArray.pop();
num2 =numArray.pop();
int pop = operateArray.pop();
int cal = StackArray.cal(num1, num2, (char) pop);
numArray.push(cal);
operateArray.push(ch);
}else{
operateArray.push(ch);
}
}
}else{
funNum+=ch;
if (i==expression.length()-1){
numArray.push(Integer.parseInt(funNum));
}else {
if (StackArray.isOperate(expression.subSequence(i + 1, i + 2).charAt(0))) {
numArray.push(Integer.parseInt(funNum));
funNum="";
}
}
}
}
while (true){
if (operateArray.isEmpty()){
break;
}
num1 = numArray.pop();
num2 =numArray.pop();
int pop = operateArray.pop();
int cal = StackArray.cal(num1, num2, pop);
numArray.push(cal);
}
if (operateArray.isEmpty()){
res=numArray.pop();
System.out.println("结算得到的结果:"+expression+":"+res);
}
}
}
class StackArray {
public int maxSize;
public int top;
public int [] stack;
public StackArray(int maxSize){
this.maxSize=maxSize;
this.top=-1;
this.stack=new int[maxSize];
}
public boolean isFull(){
return top==maxSize-1;
}
public boolean isEmpty(){
return top==-1;
}
public void push(int num){
if (isFull()){
System.out.println("栈已满,请出栈~~~");
}else{
top++;
stack[top]=num;
}
}
public int peek(){return stack[top];}
public int pop(){
if (isEmpty()){
throw new RuntimeException("栈为空,请入栈~~~");
}
int value=stack[top];
top--;
System.out.println("出栈的值为:"+value);
return value;
}
public void show(){
if (isEmpty()){
throw new RuntimeException("栈为空,请入栈~~~");
}
for (int i = top; i >=0 ; i--) {
System.out.println("a["+i+"]"+"="+stack[i]);
}
}
public static boolean isOperate(char num){
return num=='+'||num=='-'||num=='*'||num=='/';
}
public int priority(char num){
int result=0;
if (num=='+'||num=='-'){
result=-1;
}else if (num=='*'||num=='/'){
result=1;
}else{
result=0;
}
return result;
}
public static int cal(int num1,int num2,int character){
int res=0;
switch (character){
case '+':
res=num1+num2;
break;
case '-':
res=num2-num1;
break;
case '*':
res=num1*num2;
break;
case '/':
res=num2/num1;
break;
default:
break;
}
return res;
}
}