您当前的位置: 首页 >  Java

小志的博客

暂无认证

  • 0浏览

    0关注

    1217博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

java数据结构和算法——完整版的逆波兰计算器的应用示例

小志的博客 发布时间:2020-07-30 22:14:53 ,浏览量:0

一、完整版的逆波兰计算器的支持
  • 支持+ - * / ( )
  • 支持多位数及小数
  • 兼容处理,过滤任何空白字符,包括空格、制表符、换页符
二、完整版的逆波兰计算器代码示例

1、代码如下:

package com.rf.springboot01.dataStructure.stack.reversePolishNotation;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import java.util.regex.Pattern;

/**
 * @description: 完整版的逆波兰计算器
 *                 1、支持+ - * / ( )
 *                 2、支持多位数及小数,
 *                 3、兼容处理,过滤任何空白字符,包括空格、制表符、换页符
 * @author: xiaozhi
 * @create: 2020-07-29 22:28
 */
public class ReversePolishMultiCalc {

    //匹配 + - * /运算符
    public static final String SYMBOL="\\+|-|\\*|/|\\(|\\)";
    public static final String LEFT="(";
    public static final String RIGHT=")";
    public static final String ADD="+";
    public static final String SUB="-";
    public static final String MUL="*";
    public static final String DIV="/";

    //运算符等级
    public static final int LEVEL_1=1;// + - 符号等级
    public static final int LEVEL_2=2;// * / 符号等级
    public static final int LEVEL_HIGHT=Integer.MAX_VALUE;//括号() 符号的等级

    //定义栈
    static Stack stack =new Stack();
    static List data= Collections.synchronizedList(new ArrayList());

    //去除所有空白符
    public static String replaceAllBlank(String str){
        // \\s+匹配任何空白字符,包括空格、制表符、换页符等等,等价于[\f\n\r\t\v]
        return str.replaceAll("\\s+","");
    }

    // 是否是数字 int  long float double
    public static boolean isNumber(String str){
        //提取字符串中自定的字符
        Pattern pattern = Pattern.compile("^[-\\+]?[.\\d]*$");
        return pattern.matcher(str).matches();
    }

    //判断是不是运算符
    public static boolean isSymbol(String str){
        return str.matches(SYMBOL);
    }

    //匹配运算等级
    public static int calcLevel(String str){
        if("+".equals(str) || "-".equals(str)){
            return LEVEL_1;
        }else if("*".equals(str)|| "/".equals(str)){
            return LEVEL_2;
        }
        return LEVEL_HIGHT;

    }
    
    //匹配
    public static List doMatch (String s) throws Exception{
        if(s == null || "".equals(s.trim())) throw new RuntimeException("data is empty");
        if(!isNumber(s.charAt(0)+"")) throw new RuntimeException("data illeagle,start not with a number");

        s = replaceAllBlank(s);

        String each;
        int start = 0;

        for (int i = 0; i  calcLevel(stack.peek())) && calcLevel(each)             
关注
打赏
1661269038
查看更多评论
0.0413s