美文网首页程序员
用栈实现简易计算器

用栈实现简易计算器

作者: YAOPRINCESS | 来源:发表于2020-07-04 00:34 被阅读0次

    结果

    image.png

    缺点

    • 不支持()
    • 不支持浮点运算
    • 5/2=2,会损失精度,你需要把变量由int变为float

    BUG

    这个程序看起来是从右往左计算的
    当出现1-2+3
    结果就会是1-(2+3)= - 4
    还有待完善把

    完整测试代码

    import java.util.Scanner;
    
    /**
     * @author klr
     * @create 2020-07-03-22:12
     */
    public class calculator {
    
        private String expression;
    
        public String getExpression() {
            return expression;
        }
    
        public void setExpression(String expression) {
            this.expression = expression;
        }
    
        public calculator(String expression) {
            this.expression = expression;
        }
    
        public static void main(String[] args) throws Exception {
    
            System.out.println("请输入计算表达式:");
            Scanner scanner = new Scanner(System.in);
            calculator calculator = new calculator(scanner.nextLine());
            //计算结果
            System.out.println("计算结果");
            System.out.println(calculator.cal());
    
        }
    
        public int cal() throws Exception {
    
            //操作数栈
            ArrayStack1 numberStack = new ArrayStack1(10);
            //操作符栈
            ArrayStack1 operatorStack = new ArrayStack1(10);
            int loop = expression.length();
            int index = 0;
            int num1=0;
            int num2=0;
            int result=0;
            String num="";//拼接数字
            char operator=' ';
            boolean flag =false;
            while (loop > 0) {
                //如果是操作符
                if (isOperator(expression.charAt(index))) {
                    //如果操作符栈为空则直接填入栈
                    if (operatorStack.isEmpty()) {
                        operatorStack.push(expression.charAt(index));//42=*
                        index++;
                        loop--;
                        continue;
                    }
                    //如果当前操作符小于栈顶操作符则弹出两个操作数和一个操作符进行运算
                    while (priority(expression.charAt(index)) < priority((char) operatorStack.peek())) {
                        num2=numberStack.pop();
                        num1=numberStack.pop();
                        operator= (char) operatorStack.pop();
                        switch (operator) {
                            case '+':
                                result=num1+num2;
                                break;
                            case '-':
                                result=num1-num2;
                                break;
                            case '*':
                                result=num1*num2;
                                break;
                            case '/':
                                result=num1/num2;
                                break;
                            default:
                                break;
                        }
                        numberStack.push(result);
                        if(!operatorStack.isEmpty()){
                            if (priority(expression.charAt(index)) >= priority((char) operatorStack.peek())) {
                                operatorStack.push(expression.charAt(index));
                                index++;
                                loop--;
                                flag=true;//push后就可以重新开始了
                                break;
                            }
                        }
                        else {
                            operatorStack.push(expression.charAt(index));
                            index++;
                            loop--;
                            flag=true;//push后就可以重新开始了
                            break;
                        }
    
                    }
                    if (flag) {
                        flag=false;
                        continue;
                    }
                    operatorStack.push(expression.charAt(index));
                    index++;
                    loop--;
                    continue;
                }
                else {
                    if (index == expression.length() - 1) {
                        numberStack.push(expression.charAt(index)-48);
                        index++;
                        loop--;
                    }
                    else{
                        num=num + expression.charAt(index);
                        while (((index+1)<expression.length())&&!isOperator(expression.charAt(index+1))){
                            num = num+expression.charAt(index + 1);
                            index++;
                            loop--;
                        }
                        numberStack.push(Integer.parseInt(num));
                        num="";//num一定要清零
                        index++;
                        loop--;
                    }
                }
            }
    
    
            while (!operatorStack.isEmpty()){
                num2=numberStack.pop();
                num1=numberStack.pop();
                operator= (char) operatorStack.pop();
                switch (operator) {
                    case '+':
                        result=num1+num2;
                        break;
                    case '-':
                        result=num1-num2;
                        break;
                    case '*':
                        result=num1*num2;
                        break;
                    case '/':
                        result=num1/num2;
                        break;
                    default:
                        break;
                }
                numberStack.push(result);
            }
            return numberStack.pop();
        }
    
        //判断是否为操作符
        public boolean isOperator(char ch){
            return ch=='+'||ch=='-'||ch=='*'||ch=='/';
        }
    
        //判断操作符优先级
        public int priority(char ch1) {
            if(ch1=='*'||ch1=='/'){
                return 1;
            } else if (ch1 == '+' || ch1 == '-') {
                return 0;
            }
            else
                return -1;
        }
    }
    
    class ArrayStack1 {
    
        private int top = -1;//top标识栈顶,初始化为-1
    
        private int maxSize;//栈的大小
    
        private int[] stack;//栈
    
        public ArrayStack1(int size) {
            maxSize = size;
            stack = new int[maxSize];
        }
    
        //查看栈顶
        public int peek() throws Exception {
            if (isEmpty()) {
                throw new Exception("栈为空");
            }
            return stack[top];
        }
    
        //判断栈是否已满
        public boolean isFull() {
            if (top == maxSize - 1) {
                return true;
            }
            return false;
        }
    
        //判断栈是否为空
        public boolean isEmpty() {
            if (top == -1) {
                return true;
            }
            return false;
        }
    
        //元素入栈
        public void push(int value) {
            if (isFull()) {
                System.out.println(("栈已满,无法添加"));
                return;
            }
            stack[++top] = value;
        }
    
        //元素出栈
        public int pop() throws Exception {
            if (isEmpty()) {
                throw new Exception("栈已空,无法出栈");
            }
            return stack[top--];
        }
    
        //展示栈
        public void list() {
            if (isEmpty()) {
                System.out.println("栈全空");
                return;
            }
            for (int i = top; i >= 0; i--) {
                System.out.printf("stack[%d]=%d\n",i,stack[i]);
            }
        }
    }
    

    相关文章

      网友评论

        本文标题:用栈实现简易计算器

        本文链接:https://www.haomeiwen.com/subject/hzlyqktx.html