用栈实现简易计算器(JAVA)

用栈实现简易计算器

在这里插入图片描述

理解:就是运算的顺序,如同自己计算时,碰到优先级先进行运算,最后省下来的都是同一个优先级的,最后再集体运算,而栈实现了回溯的功能,能够找上一个的元素

使用了中缀表达式,加入括号使用后缀表达式。

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 = ' '; //将扫描到的char保存到ch
        String keyNum = ""; //用于拼接多位数
        while (true){
            //依次得到每个express的每一个字符
            ch = expression.substring(index,index+1).charAt(0);
            if(operStack.isOper(ch)){ //如果是运算符
                //判断当前符号栈是否为空
                if(!operStack.isEmpty()){
                    //如果符号栈里头有操作符,就进行比较,如果放弃操作符优先级小于栈中的操作符,就需要从栈中pop出两个数,
                    //在符号栈中pop出一个一个符号,将得到结果进行入栈,然后把当前的符号进栈
                    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;
    }

}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值