美文网首页
Java利用栈实现四则运算计算器

Java利用栈实现四则运算计算器

作者: 谁的青春不迷茫_5c6a | 来源:发表于2020-05-16 18:32 被阅读0次

    说明

    • 本程序只实现了基本的四则运算,即加减乘除,不能有括号
    • 本程序使用了基本的数据结构之一——栈

    源代码

    Calculator 这个类是主类,其中用到的ArrayStack 是自定义的类,源代码在后面

    public class Calculator {
    
        public static void main(String[] args) {
            
            // 表达式字符串,需要替换成你用的
            String exp = "700-400+20*60-40/2*2";
            // 数栈和符号栈
            ArrayStack numStack = new ArrayStack(20);
            ArrayStack operStack = new ArrayStack(20);
            
            int index = 0;
            // 运算数和运算符
            int num1 = 0;
            int num2 = 0;
            int oper = 0;
            // 中间结果
            int result = 0;
            char ch = ' ';
            // 多位数字字符串
            String num="";
            
            // 遍历表达式
            while(index < exp.length()) {
                // 截取字符
                ch = exp.substring(index, index+1).charAt(0);
                // 判断该字符是数字还是运算符
                if(operStack.isOper(ch)) {
                    // 判断符号栈是否为空
                    if(!operStack.isEmpty()) {
                        // 如果当前运算符的优先级 <= 栈顶运算符的优先级
                        if(operStack.priority(ch) <= operStack.priority(operStack.peek())) {
                            // 取出数栈最上面的两个数
                            num1 = numStack.pop();
                            num2 = numStack.pop();
                            // 取出符号栈的栈顶运算符
                            oper = operStack.pop();
                            // 进行运算
                            result = numStack.cal(num1, num2, oper);
                            // 运算结果入数栈
                            numStack.push(result);
                            // 当前运算符入符号栈
                            operStack.push(ch);
                            
                        }else {
                            // 如果当前运算符的优先级 > 栈顶运算符,直接入栈
                            operStack.push(ch);
                        }
                    }else {
                        // 如果当前符号栈为空,直接入栈
                        operStack.push(ch);
                    }
                }else {
                    // 如果是数字,不能直接入栈,因为它可能不止一位
                    // 拼接字符
                    num += ch;
                    
                    // 如果是最后一位数字,就没必要判断了,直接入栈好了
                    if(index == exp.length()-1) {
                        numStack.push(Integer.parseInt(num));
                    }else {
                        // 判断当前位置的下一位是不是数字,如果是运算符,就可以入栈了;否则继续循环
                        if( operStack.isOper(exp.substring(index+1,index+2).charAt(0) ) ){
                            numStack.push(Integer.parseInt(num));
                            // 然后把字符串清空
                            num = "";
                        }
                    }
                    
                }
                
                index++;
            }   // 表达式遍历结束
            
            // 顺序从数栈和符号栈取出 运算数和运算符进行运算,最终符号栈为空,数栈中只剩下最终结果
            while(true) {
                if(operStack.isEmpty()) {
                    break;
                }
                num1 = numStack.pop();
                num2 = numStack.pop();
                oper = operStack.pop();
                result = numStack.cal(num1, num2, oper);
                numStack.push(result);
            }
            
            // 输出最终结果
            System.out.printf("%s = %d\n", exp, numStack.pop());
        }   // 主方法结束
    
    }   // 类结束
    
    

    这是ArrayStack 类的源代码

    
    public 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 == this.maxSize-1;
        }
        // 判断栈空
        public boolean isEmpty() {
            return top == -1;
        }
        // 入栈dea
        public void push(int ele) {
            if(isFull()) {
                return;
            }
            top++;
            stack[top] = ele;
        }
        // 出栈
        public int pop() {
            if(isEmpty()) {
                throw new RuntimeException("栈为空!");
            }
            int value = stack[top];
            top--;
            return value;
        }
        // 查看栈顶元素 
        public int peek() {
            if(isEmpty()) {
                throw new RuntimeException("栈为空!");
            }
            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]);
            }
        }
        // 返回运算符优先级
        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 result = 0;
            switch(oper) {
            case '+':
                result = num1 + num2;
                break;
            case '-':
                result = num2 - num1;   // 注意出栈的顺序与实际顺序是反着的
                break;
            case '*':
                result = num1 * num2;
                break;
            case '/':
                result = num2 / num1;
                break;
            }
            
            return result;
        }
        
    }
    
    

    运行结果

    运行结果

    相关文章

      网友评论

          本文标题:Java利用栈实现四则运算计算器

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