⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 calculatestring.java

📁 进行四则运算"+-*/^ ",并可以处理简单变量"AB",并且具备可扩展性.
💻 JAVA
字号:


import java.math.BigDecimal;   
import java.util.ArrayList;   
import java.util.List;   
import java.util.regex.Matcher;   
import java.util.regex.Pattern;   
public class CalculateString {   
	final int VARIABLE = 1;
	final int NUMBER = 2;
	public String variable;
	public double value;
	public String function;
	public int number_of_arguments;
	
	public void Variable( String variable, double value )
	{
		this.variable=variable;
	    this.value=value;
	}
	public void Function( String function, int number_of_arguments )
    {
	    this.function=function;
	    this.number_of_arguments=number_of_arguments;
    }
	
    public BigDecimal calculateString(String str)     //计算表达式
    {   
        char[] strs = str.toCharArray();          //返回输出数组的拷贝
        Stack<String> stack = new Stack<String>();   

        for (int i = 0; i < strs.length; i++)
        {  
            String stackStr = String.valueOf(strs[i]);   //将strs中的字符转换为字符串,并返回
            stack.push(stackStr);   //压入栈中

            if ( ")".equals(stack.top()) )               //如果是")"继续寻找
            {   
                String subStr = null;   
                while (!"(".equals(stack.top())) 
                {   
                    stack.pop();   
                    if (!"(".equals(stack.top())) 
                    {   
                        subStr = addEnd(subStr, stack.top());   
                    }   
                }   
                String pushStr = CalculateReversePolishExpression(subStr);   
                stack.pop();   
                stack.push(pushStr);   
            }   
  
        }   
        String resultStr = null;   
        while (stack.count != 0) 
        {   
            resultStr = CalculateReversePolishExpression(stack.toString());   
        }   
        BigDecimal result = null;   
        if (resultStr != null) 
        {   
            result = new BigDecimal(resultStr);   
        } else 
        {   
            result = BigDecimal.ZERO;   //让result的值为0.标度为0;
        }  
	
        return result.setScale(2, BigDecimal.ROUND_HALF_UP); //返回一个 BigDecimal,其标度为指定值
    													//向"最接近的"数字舍入,如果与两个相邻数字的距离相等,
														//则为向上舍入的舍入模式。 
    }   
 
    public String[] matcher(String regex, String str) {   //匹配器
        Pattern pattern = Pattern.compile(regex);   //将正则表达式编译到模式中
        Matcher matcher = pattern.matcher(str);   //创建匹配给定输入与此模式的匹配器
        List<String> list = new ArrayList<String>();   
        while (matcher.find()) {   
            list.add(matcher.group());   
        }   
        String[] result = new String[list.size()];   
        return list.toArray(result);  
        
    }   
  
    public List<String> createReversePolishExpression(String subStr) {   //构造逆波兰表达式
        String regex = "\\d+\\.{0,1}\\d*";   
        String[] numbers = matcher(regex, subStr);   
        String changeStr = subStr.replaceAll(regex, "0").replaceAll("\\-\\-0",   
                "-1").replaceAll("\\+\\-0", "+1").replaceAll("\\*\\-0", "*1")   //用正则表达式来匹配
                .replaceAll("\\/\\-0", "/1");   
        char[] chars = changeStr.toCharArray();   
        int index = 0;   
        List<String> list = new ArrayList<String>();  //指针列表
        
        for (int i = 0; i < chars.length; i++) {   
            String str = String.valueOf(chars[i]);   
            if ("0".equals(str)) {   
                list.add(numbers[index++]);   
            } else if ("1".equals(str)) {   
                list.add("-" + numbers[index++]);   
            } else {   
                list.add(str);   
            }   
        }   
        List<String> suffix = new ArrayList<String>();   
        Stack<String> operator = new Stack<String>();   
        for (int i = 0; i < list.size(); i++) {   
            if (!isOperatorType(list.get(i))) {   
                suffix.add(list.get(i));   
            } else {   
                if (operator.count == 0) {   
                    operator.push(list.get(i));   
                } else {   
                    while (operator.count != 0&&compare(operator.top(), list.get(i)) >= 0) {   
                        String top = operator.top();   
                        operator.pop();   
                        suffix.add(top);   
                    }    
                    operator.push(list.get(i));   
  
                }   
            }   
        }   
  
        while (operator.count != 0) {   
            suffix.add(operator.top());   
            operator.pop();   
        }  
      //  System.out.println(suffix);
        return suffix;   
    }  
 
    public String CalculateReversePolishExpression(String subStr) {   //计算逆波兰表达式
        List<String> suffix = createReversePolishExpression(subStr);   
        Stack<Double> stack = new Stack<Double>();   
        
        for (int i = 0; i < suffix.size(); i++) 
        {   
            if (!isOperatorType(suffix.get(i))) 
            {   
            	if(!isVarableType(suffix.get(i)))
            	{
            														   //在这里要判断是否为变量
            		stack.push(Double.valueOf(suffix.get(i)));        //是数字的话压入栈
            	}
            	else
            	{	
            		if(suffix.get(i).equals("A"))
            		{
            			Variable("A",1);
            			stack.push(value);
            		}
            		if(suffix.get(i).equals("B"))
            		{
            			Variable("B",2);
            			stack.push(value);
            			
            		}
            	}
            } 
            else 
            {   
                Double current = stack.top();   
                stack.pop();   
                Double previous = null;   
                if (stack.count != 0) {   
                    previous = stack.top();   
                    stack.pop();   
                } else {   
                    previous = new Double(0);   
                }   
                Double result = calculate(suffix.get(i), previous, current);   
                stack.push(result);   
            }   
        }   
        return stack.top().toString();   
    }   
  
    public String addEnd(String str, String a) {   
        StringBuffer buf = new StringBuffer();   
        buf.append(a);                         //将a添加到当前字符串的尾部
        if (str != null) {   
            buf.append(str);   
        }   
        return buf.toString();                  //转换成字符串形式
    }   
  
    public boolean isOperatorType(String str) {   //判断操作符类型,如果是"+-*/%^"则返回true
        if (str.equals("+") || str.equals("-") || str.equals("*")   
                || str.equals("/") || str.equals("^") || str.equals("%")) {   
            return true;   
        }   
        return false;   
    }   
    public boolean isVarableType(String str) {   //判断操作符类型,如果是"AB"则返回true
        if (str.equals("A") || str.equals("B")) 
        {   
            return true;   
        }   
        return false;   
    }   
  
    public int compare(String op1, String op2) {      //比较操作符的优先级
        Integer iop1 = getOperator(op1);   
        Integer iop2 = getOperator(op2);   
        return iop1.compareTo(iop2);   
    }   
  
    public Integer getOperator(String op) {      //定义操作符优先级
        if ("+".equals(op) || "-".equals(op)) 
        {   
            return new Integer(0);   
        }   
        if ("*".equals(op) || "/".equals(op) || "%".equals(op)) 
        {   
            return new Integer(1);   
        }
        if ("^".equals(op)) 
        {   
            return new Integer(2);   
        }
        return null;   
    }   
  
    public Double calculate(String op, Double previous, Double current) {   //各种符号的计算
        if ("+".equals(op)) 
        {   
            return previous + current;   
        }   
        if ("-".equals(op)) 
        {   
            return previous - current;   
        }   
        if ("*".equals(op)) 
        {   
            return previous * current;   
        }   
        if ("/".equals(op)) 
        {   
            return previous / current;   
        } 
        if ("%".equals(op)) 
        {   
            return previous % current;   
        } 
        if ("^".equals(op)) 
        {   
            return Math.pow(previous, current);   
        }  
        return null;   
    }   

    public static void main(String[] args) {   
        String strs = "(2^B+A*B)/3";

        BigDecimal result = new CalculateString().calculateString(strs);   
        System.out.println(result.toString());   
      
           
    }   
  
}  

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -