public static void main(String[] args) {
//完成表达式运算
String s="30+2*5-6+7";
//创建两个栈 一个数栈 一个符号栈
ArrayStack arrayStack=new ArrayStack(10);
ArrayStack arrayStack1=new ArrayStack(10);
int index=0;
int num1=0;
int num2=0;
int oper=0;
int res=0;
char ch=' ';
String keepnum="";
while (true)
{
//依次得到s中的每一个字符
ch=s.charAt(index);
if(!arrayStack.isOper(ch))
{
keepnum+=ch;
if(index==s.length()-1)
arrayStack.push(ch-48);
else
{
if(arrayStack.isOper(s.charAt(index+1)))
{
arrayStack.push(Integer.parseInt(keepnum));
System.out.println(keepnum);
keepnum="";
}
}
}
else if(arrayStack.isOper(ch))
{
if(arrayStack1.isEmpty())
{
arrayStack1.push(ch);
}
else if(arrayStack.priority(ch)<=arrayStack.priority(arrayStack1.peek()))
{
num1=arrayStack.pop();
num2=arrayStack.pop();
oper=arrayStack1.pop();
res=arrayStack.cal(num1,num2,oper);
arrayStack.push(res);
arrayStack1.push(ch);
}
else
{
arrayStack1.push(ch);
}
}
if(index==s.length()-1)
{
break;
}
index++;
}
while (!arrayStack1.isEmpty())
{
num1=arrayStack.pop();
num2=arrayStack.pop();
oper=arrayStack1.pop();
res=arrayStack.cal(num1,num2,oper);
arrayStack.push(res);
}
System.out.println(arrayStack.pop());
}
}
//定义一个栈 增加一些功能
class ArrayStack
{
private int maxSize;
private int[]stack;
private int top=-1;
public ArrayStack(int maxSize)
{
this.maxSize=maxSize;
stack=new int[this.maxSize];
}
//判断栈满
public boolean isFull()
{
return top==maxSize-1;
}
//判断栈空
public boolean isEmpty()
{
return top==-1;
}
//入栈
public void push(int val)
{
if( isFull()) return;
top++;
stack[top]=val;
}
//出栈
public int pop()
{
if(isEmpty()) return -1;
int val=stack[top];
top--;
return val;
}
//显示栈顶
public int peek()
{
if(isEmpty()) return -1;
int val=stack[top];
return val;
}
//返回运算符的优先级 优先级使用数字表示 数字越大 优先级越高
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 = num2 / num1;
break;
case '*':
res = num1 * num2;
default:
break;
}
return res;
}
栈实现计算器
最新推荐文章于 2024-06-06 14:29:15 发布