计算器四则运算实现代码—java

本文介绍了使用堆栈后缀表达式计算法来实现Java计算器的四则运算,包括处理括号内的优先计算,通过循环逐步解决复杂表达式。
摘要由CSDN通过智能技术生成

一、例用堆栈后缀表达式计算

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Stack;



public class CalculateService {
    static final String symbol = "+-*/()";
    static final String[] priority = {"+-", "*/", "()"};
    static Comparator<String> comp = new Comparator<String>() {
        public int compare(String s1, String s2) {
            int n1 = 0;
            int n2 = 0;
            for (int i = 0; i < priority.length; i++) {
                if (priority[i].indexOf(s1) >= 0) {
                    n1 = i;
                }
                if (priority[i].indexOf(s2) >= 0) {
                    n2 = i;
                }
            }
            return n1 - n2;
        }
    };

    public static final String REGEX_SPACE = "\\s*";
    public static final String STRING_EMPTY = "";

    public static String handleInputExpression(String expression) {
        List<String> suffixList = null;
        String resultString = null;
        try {
            List<String> infixList = CalculateService.toInfixExpressionList(expression);
            suffixList = infixToSuffix(infixList);

            double doubleResult = calculator(suffixList);
            int intResultInt = new Double(doubleResult).intValue();
            resultString = String.valueOf(intResultInt);
            System.out.println("input = " + expression + " ,result = " + resultString);
        } catch (Exception e) {
            resultString = "illegal expression!";
        }
        return resultString;
    }

    /**
     * 中缀表达式转后缀表达式
     */
    public static List<String> infixToSuffix(List<String> expression) throws Exception {
        if (expression == null) {
            throw new Exception("illegal expression!");
        }

        List<String> suffixList = new ArrayList<String>();
        Stack<String> operatorStack = new Stack<String>();

        StringBuffer buffer = new StringBuffer();
        for (String item : expression) {
            if (symbol.indexOf(item) >= 0) // 是运算符
            {
                if (item.equals("(")) // 左括号直接入栈
                {
                    operatorStack.push(item); // 入栈
                } else i
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值