运行结果不正确,一直报栈为空的错误
创建两个栈,读取字符串,如果读取到的字符是数字,将它存入数栈,如果存入的字符是符号,则比较符号和栈顶符号的优先级,如果优先级小于栈顶的符号,则取出数栈的两个数和符号栈的符号进行运算,将计算出的结果存入数栈,将符号存入符号栈。如果优先级大于栈顶的符号直接将符号添加入栈,如果栈为空,直接添加入栈。写一个while循环将数栈和符号栈的数据取出进行运算,当符号栈中的数据为空时结束循环。
用数组模拟栈实现计算机的效果
public class Calculators {
public static void main(String[] args) {
//根据前面老师的思路,完成表达式的运算
String str="3+2*6-2";
//创建两个数栈,一个符号栈
ArraysStack1 num=new ArraysStack1(10);
ArraysStack1 fuhao=new ArraysStack1(10);
//定义需要的相关变量
int index=0;//用于扫描
int num1=0;
int num2=0;
int oper=0;
int res=0;
char ch=' ';//将每次扫描得到的char保存到ch中
//开始循环的扫描expression
while (true){
//依次得到str中的每一个字符
ch=str.substring(index,index+1).charAt(0);
//判断是什么,然后做相应的处理
if(fuhao.isOper(ch)){//如果是运算符
if(fuhao.isEmpty()){
fuhao.push(ch);
}else{
if(fuhao.priority(ch)<=fuhao.priority(fuhao.peek())){
num1=num.pop();
num2=num.pop();
oper=fuhao.pop();
res=num.cal(num1,num2,oper);
//帮运算的结果入数栈
num.push(res);
fuhao.push(ch);
}else if(fuhao.priority(ch)>fuhao.priority(fuhao.peek())){
//如果当前的操作符的优先级大于栈中的操作符,就直接入符号栈
fuhao.push(ch);}
// }else {
// fuhao.push(ch);
// }
//
}
}else {
//如果是数,则直接入数栈
num.push(ch-48);
}
//让index+1,并判断是否扫描到
index++;
if(index>=str.length()){
break;
}
}
while (true){
//如果符号栈为空,则计算到最后的结果,数栈中只有一个数字
if(fuhao.isEmpty()){
break;
}
//
num1=num.pop();
num2=num.pop();
oper=fuhao.pop();
res=num.cal(num1,num2,oper);
num.push(res);
System.out.println(num.pop());
}
}
}
//定义一个类表示栈
class ArraysStack1{
private int maxSize;//栈的大小
private int[]stack;//数组,数组模拟栈,数据就放在该数组中
private int top=-1;//top表示栈顶
public ArraysStack1(int maxSize) {
this.maxSize = maxSize;
stack=new int[this.maxSize];
}
public boolean isFull(){
return top==maxSize-1;
}
//栈空
public boolean isEmpty(){
return top==-1;
}
//入栈-push
public void push(int value){
//先判断栈是否满
if(isFull()){
System.out.println("栈满");
}
top++;
stack[top]=value;
}
//将栈顶的数据返回
public int pop(){
//先判断栈是否空
if(isEmpty()){
//抛出异常
throw new RuntimeException("栈空,没有数据");
}
int value =stack[top];
top--;
return value;
}
//显示栈的情况
//遍历时需要从栈顶开始显示数据
public void list1(){
if(isEmpty()){
System.out.println("栈空没有数据");
return;
}
for (int t = top; t >=0 ; t--) {
System.out.println(t+":"+stack[t]);
}
}
//返回运算符的优先级,优先级是程序员来定的,优先级使用数组表示
//数字越大则优先级就越高
public int priority(int oper){
if(oper =='*'||oper=='/'){
return 1;
}else if(oper=='+'||oper=='-'){
return 0;
}else {
return -1;
}
}
//增加一个方法,可以返回当前栈顶的值,但是不是真正的pop
public int peek(){
return stack[top];
}
//判断是不是一个运算符
public boolean isOper(char val){
return val=='+'||val=='-'||val=='*'||val=='/';
}
//计算方法
public int cal(int num1,int num2,int oper){
int res=0;//res用来存放计算的结果
switch(oper){
case '+':
res=num1+num2;
break;
case '-':
res=num2-num1;
break;
case '*':
res=num2*num1;
case'/':
res=num2/num1;
}
return res;
}
}