计算公式(java实现)

import java.util.Stack;

public class 计算器 {
    public static void main(String[] args) {
        String formula="3+2*2";
        System.out.println(a.getResult(formula));
    }

    private static boolean isRightFormat = true;

    public static int getResult(String formula){
        int returnValue = 0;
        try{
            returnValue = doAnalysis(formula);
        }catch(NumberFormatException nfe){
            nfe.printStackTrace();
        }catch(Exception e){
            e.printStackTrace();
        }
        if(!isRightFormat){
            System.out.println(("公式格式有误,请检查:" + formula));
        }
        return returnValue;
    }


    //先解决括号的问题
    private static int doAnalysis(String formula){
        int returnValue = 0;
        LinkedList<Integer> stack = new LinkedList<Integer>();
        int curPos = 0;
        String beforePart = "";
        String afterPart = "";
        String calculator = "";
        isRightFormat = true;
        while(isRightFormat&&(formula.indexOf('(') >= 0||formula.indexOf(')') >= 0)){
            curPos = 0;
            for(char s : formula.toCharArray()){
                if(s == '('){
                    stack.add(curPos);
                }else if(s == ')'){
                    if(stack.size() > 0){
                        beforePart = formula.substring(0, stack.getLast());
                        afterPart = formula.substring(curPos + 1);
                        calculator = formula.substring(stack.getLast() + 1, curPos);
                        formula = beforePart + doCalculation(calculator) + afterPart;
                        stack.clear();
                        break;
                    }else{
                        System.out.println("有未关闭的右括号!");
                        isRightFormat = false;
                    }
                }
                curPos++;
            }
            if(stack.size() > 0){
                System.out.println("有未关闭的左括号!");
                break;
            }
        }
        if(isRightFormat){
            returnValue = doCalculation(formula);
        }
        if(returnValue==0){
            returnValue =0;
        }
        return returnValue;
    }


    private static int doCalculation(String formula) {
        Stack<Integer> stack = new Stack<Integer>();
        int preVal = '+';//记录前一个运算符
        int len=formula.length();
        for (int i = 0; i < len; i++) {
            char element = formula.charAt(i);
            //过滤空格
            if (element == ' ')
                continue;
            if (Character.isDigit(element)) { // 如果是数字就放入栈中
                int num = 0;
                while (Character.isDigit(element) && i<len) {
                    num = num * 10 + element - '0';
                    i++;
                    if (i < len)
                        element = formula.charAt(i);
                }
                i--;//这个是为了抵消上面for循环中的i++
                //记录每个数字前面的符号,如果是乘号和除号就直接和前面的数字运算
                if(preVal=='*')
                    stack.push(stack.pop() * num);
                if(preVal=='/')
                    stack.push(stack.pop() / num);
                //记录每个数字前面的符号,如果是加号或者减号就直接放入栈中
                if(preVal=='+')
                    stack.push(num);
                if(preVal=='-')
                    stack.push(-num);
            }else {//记录当前的符号
                preVal = element;
            }
        }
        //再将栈中的所有元素进行加和
        int res=0;
        for (int num :stack) {
            res+=num;
        }
        return res;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值