欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java代码执行字符串中的逻辑运算方法

程序员文章站 2023-12-22 19:34:46
方式一 public class test { public static void main(string[] args) throws exceptio...

方式一

public class test
{
 public static void main(string[] args) throws exception {
   string str = "(a or b) and c";
   str = str.replaceall("or", "||");
   str = str.replaceall("and", "&&");
   system.out.println(str);
   scriptenginemanager manager = new scriptenginemanager();
   scriptengine engine = manager.getenginebyname("js");
   engine.put("a",true);
   engine.put("b",false);
   engine.put("c",true);  
   object result = engine.eval_r(str);
   system.out.println("结果类型:" + result.getclass().getname() + ",计算结果:" + result);
  }
}

这种方式使用js的方式进行运算,使用较简单,但是当运算double类型的四则运算时结果会出现循环小数,运算结果会出现问题.

方式二(能够保证四则运算精度):

/**
 * @project:  bizrule  
 * @file:   org.coffeesweet.util.mathexpress.java
 * @author:  coffeesweet
 * @date:   2011-3-28
 * @description: 2011 coffeesweet inc. all rights reserved.
 */
package org.coffeesweet.util;
import java.math.bigdecimal;
import java.math.mathcontext;
import java.math.roundingmode;
import java.util.arraylist;
import java.util.linkedlist;
import java.util.list;
import java.util.stringtokenizer;
import java.util.regex.matcher;
import java.util.regex.pattern;
/**
 * @author coffeesweet
 * +,-,*,/四则运算的表达式逆波兰解析计算类,精确计算,应用bigdecimal类处理
 * 支持负数,但规范除整个表达式第一个数为负数时可以不出现在'('后,其它表达式中间任何位置的
 * 负数必须出现在'('后,即:用括号括起来。比如:-3+(-2+1)*10或-3+((-2)+1)*10或(-3)+(-2+1)*10或(-3)+((-2)+1)*10
 */
public class mathexpress {
 /**
  * +
  */
 private final static string op1 = "+";
 /**
  * -
  */
 private final static string op2 = "-";
 /**
  * *
  */
 private final static string op3 = "*";
 /**
  * /
  */
 private final static string op4 = "/";
 /**
  * ^
  */
// private final static string op5 = "^";
 /**
  * %
  */
// private final static string op6 = "%";
 /**
  * (
  */
 private final static string opstart = "(";
 /**
  * )
  */
 private final static string opend = ")";
 /**
  * !用来替代负数前面的'-'
  */
// private final static string negativesing = "!";
 /**
  * !用来替代负数前面的'+'
  */
// private final static string plussing = "@";
 /**
  * '#'用来代表运算级别最低的特殊字符
  */
// private final static string lowestsing = "#";
 //最原始的四则运算式
 private string expbase;
 //经过初始化处理后的四则运算式
 private string expinited;
 //精度
 private int precision=10;
 //取舍模式
 private roundingmode roundingmode=roundingmode.half_up;
 //精度上下文
 private mathcontext mc;
 //四则运算解析
 private list<string> explist = new arraylist<string>();
 //存放逆波兰表达式
 private list<string> rpnlist = new arraylist<string>();
 public mathexpress(){
 }
 public mathexpress(string expbase) {
  init(expbase,this.precision,this.roundingmode);
 }
 public mathexpress(string expbase,int precision,roundingmode roundingmode){
  init(expbase,precision,roundingmode);
 }
 public void init(string expbase,int precision,roundingmode roundingmode){
  this.expbase = expbase;
  this.precision = precision;
  this.roundingmode = roundingmode;
  this.mc = new mathcontext(precision,roundingmode);
  this.expinited = initexpress(expbase);
  stringtokenizer st = new stringtokenizer(this.expinited,"+-*/^%()",true);
  while(st.hasmoreelements()){
   this.explist.add(st.nextelement().tostring().trim());
  }
  this.rpnlist = initrpn(this.explist);
 }
 /**
  * @return the expbase
  */
 public string getexpbase() {
  return expbase;
 }
 /**
  * @param expbase the expbase to set
  */
 public void setexpbase(string expbase) {
  this.expbase = expbase;
 }
 /**
  * @return the expinited
  */
 public string getexpinited() {
  return expinited;
 }
 /**
  * @param expinited the expinited to set
  */
 public void setexpinited(string expinited) {
  this.expinited = expinited;
 }
 /**
  * @return the precision
  */
 public int getprecision() {
  return precision;
 }
 /**
  * @param precision the precision to set
  */
 public void setprecision(int precision) {
  this.precision = precision;
 }
 /**
  * @return the roundingmode
  */
 public roundingmode getroundingmode() {
  return roundingmode;
 }
 /**
  * @param roundingmode the roundingmode to set
  */
 public void setroundingmode(roundingmode roundingmode) {
  this.roundingmode = roundingmode;
 }
 /**
  * @return the explist
  */
 public list<string> getexplist() {
  return explist;
 }
 /**
  * @param explist the explist to set
  */
 public void setexplist(list<string> explist) {
  this.explist = explist;
 }
 /**
  * @return the rpnlist
  */
 public list<string> getrpnlist() {
  return rpnlist;
 }
 /**
  * @param rpnlist the rpnlist to set
  */
 public void setrpnlist(list<string> rpnlist) {
  this.rpnlist = rpnlist;
 }
 /**
  * @return the mc
  */
 public mathcontext getmc() {
  return mc;
 }
 /**
  * @param mc the mc to set
  */
 public void setmc(mathcontext mc) {
  this.mc = mc;
 }
 /**
  * 去除空白字符和在负号'-'前加'0',便于后面的stringtokenizer
  * @param exp
  * @return
  */
 private static string initexpress(string exp){
  string restr = null;
  restr = exp.replaceall("\\s", "");
  if(restr.startswith("-")){
   restr = "0"+restr;
  }
  restr = restr.replaceall("\\(\\-", "(0-");
  return restr;
 }
 /**
  * 是否是整数或是浮点数,但默认-05.15这种也认为是正确的格式
  * @param str
  * @return
  */
 private boolean isnumber(string str){
  pattern p = pattern.compile("^(-?\\d+)(\\.\\d+)?$");
  matcher m = p.matcher(str);
  boolean isnumber = m.matches();
  return isnumber;
 }
 /**
  * 设置优先级顺序()设置与否无所谓
  * @param sign
  * @return
  */
 private int precedence(string str){
  char sign = str.charat(0);
  switch(sign){
   case '+':
   case '-':
    return 1;
   case '*':
   case '/':
    return 2;
   case '^':
   case '%':
    return 3;
   case '(':
   case ')':
//   case '#':
   default:
    return 0;
  }
 }
 /**
  * 转变为逆波兰表达式
  * @param strlist
  * @return
  */
 public list<string> initrpn(list<string> strlist){
  list<string> returnlist = new arraylist<string>();
  //用来存放操作符的栈
  stack stack = new stack();
//  stack.push(lowestsing);
  int length = strlist.size();
  for(int i=0;i<length;i++ ){
   string str = strlist.get(i);
   if(isnumber(str)){
    returnlist.add(str);
   }else{
    if(str.equals(opstart)){
     //'('直接入栈
     stack.push(str);
    }else if(str.equals(opend)){
     //')'
     //进行出栈操作,直到栈为空或者遇到第一个左括号 
     while (!stack.isempty()) { 
      //将栈顶字符串做出栈操作 
      string tempc = stack.pop(); 
      if (!tempc.equals(opstart)) { 
       //如果不是左括号,则将字符串直接放到逆波兰链表的最后 
       returnlist.add(tempc); 
      }else{ 
       //如果是左括号,退出循环操作 
       break; 
      } 
     } 
    }else{
     if (stack.isempty()) {
      //如果栈内为空 
      //将当前字符串直接压栈 
      stack.push(str); 
     }else{
      //栈不空,比较运算符优先级顺序
      if(precedence(stack.top())>=precedence(str)){
       //如果栈顶元素优先级大于当前元素优先级则
       while(!stack.isempty() && precedence(stack.top())>=precedence(str)){
        returnlist.add(stack.pop());
       }
      }
      stack.push(str);
     }
    }
   }
  }
  //如果栈不为空,则将栈中所有元素出栈放到逆波兰链表的最后 
  while (!stack.isempty()) {
   returnlist.add(stack.pop());
  }
  return returnlist;
 }
 /**
  * 计算逆波兰表达式
  * @param rpnlist
  * @return
  */
 public string caculate(list<string> rpnlist){
  stack numberstack = new stack(); 
  int length=rpnlist.size(); 
  for(int i=0;i<length;i++){ 
   string temp=rpnlist.get(i); 
   if(isnumber(temp)){ 
    numberstack.push(temp); 
   }else{ 
    bigdecimal tempnumber1 = new bigdecimal(numberstack.pop(),this.mc);
    bigdecimal tempnumber2 = new bigdecimal(numberstack.pop(),this.mc);
    bigdecimal tempnumber = new bigdecimal("0",this.mc);
    if(temp.equals(op1)){ 
     tempnumber=tempnumber2.add(tempnumber1); 
    }else if(temp.equals(op2)){ 
     tempnumber=tempnumber2.subtract(tempnumber1); 
    }else if(temp.equals(op3)){ 
     tempnumber=tempnumber2.multiply(tempnumber1); 
    }else if(temp.equals(op4)){ 
     tempnumber=tempnumber2.divide(tempnumber1, 
       precision, 
       roundingmode); 
    } 
    numberstack.push(tempnumber.tostring()); 
   } 
  } 
  return numberstack.pop();
 }
 /**
  * 按照类的缺省参数进行计算
  * @return
  */
 public string caculate(){
  return caculate(this.rpnlist);
 }
 /**
  * 数字条件表达式精确比较
  * eg: "3.0>2" "1<5" "1==5" "1!=5" "(1.0+2)>3" "((-0.9+3)>=2. 1)"
  * 不支持&&,||等连接符
  * @param str
  * @return
  */
 public static boolean compareto(string strparm){
  boolean reboolean = false;
  boolean isparentheses = false;//标记是否有()括上整个字符串
  string str = initexpress(strparm);
  pattern p = pattern.compile("^\\([\\s\\s]*\\)$");
  matcher m = p.matcher(str);
  isparentheses = m.matches();
  if(-1==str.indexof(">=")&&-1==str.indexof("<=")&&-1==str.indexof("==")&&-1==str.indexof("!=")){
   if(-1==str.indexof(">")&&-1==str.indexof("<"))
   throw new illegalargumentexception("异常:条件表达式不正确!");
  }
  if(-1 != str.indexof(">=")){
   string[] strtemps = str.split(">=");
   if(isparentheses){
    strtemps[0] = strtemps[0] + ")";
    strtemps[1] = "(" + strtemps[1];
   }
   int r = new bigdecimal((new mathexpress(strtemps[0]).caculate())).compareto(new bigdecimal((new mathexpress(strtemps[1]).caculate())));
   if( -1 == r ){
    reboolean = false;
   }else{
    reboolean = true;
   }
  }else if(-1 != str.indexof("<=")){
   string[] strtemps = str.split("<=");
   if(isparentheses){
    strtemps[0] = strtemps[0] + ")";
    strtemps[1] = "(" + strtemps[1];
   }
   int r = new bigdecimal((new mathexpress(strtemps[0]).caculate())).compareto(new bigdecimal((new mathexpress(strtemps[1]).caculate())));
   if( 1 == r ){
    reboolean = false;
   }else{
    reboolean = true;
   }
  }else if(-1 != str.indexof("==")){
   string[] strtemps = str.split("==");
   if(isparentheses){
    strtemps[0] = strtemps[0] + ")";
    strtemps[1] = "(" + strtemps[1];
   }
   int r = new bigdecimal((new mathexpress(strtemps[0]).caculate())).compareto(new bigdecimal((new mathexpress(strtemps[1]).caculate())));
   if( 0 == r ){
    reboolean = true;
   }else{
    reboolean = false;
   }
  }else if(-1 != str.indexof("!=")){
   string[] strtemps = str.split("!=");
   if(isparentheses){
    strtemps[0] = strtemps[0] + ")";
    strtemps[1] = "(" + strtemps[1];
   }
   int r = new bigdecimal((new mathexpress(strtemps[0]).caculate())).compareto(new bigdecimal((new mathexpress(strtemps[1]).caculate())));
   if( 0 != r ){
    reboolean = true;
   }else{
    reboolean = false;
   }
  }else if((-1 != str.indexof(">")) && (-1 == str.indexof("="))){
   string[] strtemps = str.split(">");
   if(isparentheses){
    strtemps[0] = strtemps[0] + ")";
    strtemps[1] = "(" + strtemps[1];
   }
   int r = new bigdecimal((new mathexpress(strtemps[0]).caculate())).compareto(new bigdecimal((new mathexpress(strtemps[1]).caculate())));
   if( 1 == r ){
    reboolean = true;
   }else{
    reboolean = false;
   }
  }else if((-1 != str.indexof("<")) && (-1 == str.indexof("="))){
   string[] strtemps = str.split("<");
   if(isparentheses){
    strtemps[0] = strtemps[0] + ")";
    strtemps[1] = "(" + strtemps[1];
   }
   int r = new bigdecimal((new mathexpress(strtemps[0]).caculate())).compareto(new bigdecimal((new mathexpress(strtemps[1]).caculate())));
   if( -1 == r ){
    reboolean = true;
   }else{
    reboolean = false;
   }
  }
  return reboolean;
 }
 public static void main(string...args){
//  mathexpress me = new mathexpress("-(-0.5+0.1)*10+2",10,roundingmode.half_up);
//  system.out.println(me.getexplist());
//  list<string> templist = me.initrpn(me.getexplist());
//  system.out.println(templist);
//  string resultstr = me.caculate(templist);
//  system.out.println(resultstr);
  mathexpress me = new mathexpress("-(-1.5000000003+0.1)*10+2");
  string resultstr = me.caculate();
  bigdecimal bd = new bigdecimal(resultstr);
  bigdecimal bd2 = bd.setscale(2, roundingmode.half_up);
  system.out.println(me.caculate());
  system.out.println(bd.tostring());
  system.out.println(bd.scale());
  system.out.println(bd2.tostring());
  system.out.println(bd2.scale());
//  system.out.println("------------------------------------");
//  pattern p = pattern.compile("^\\([\\s\\s]*\\)$");//匹配类似以'('开头')'结尾的字符串
//  matcher m = p.matcher("(2. 0>2.22)");
//  system.out.println(m.matches());
  boolean reboolean = mathexpress.compareto("((-8.0+3)>=2. 1)");
  system.out.println(reboolean);
 }
 /**
  * 栈
  */
 private class stack {
  linkedlist<string> stacklist = new linkedlist<string>();
  public stack() {
  }
  /**
   * 入栈
   * @param expression
   */
  public void push(string expression) {
   stacklist.addlast(expression);
  }
  /**
   * 出栈
   * @return
   */
  public string pop() {
   return stacklist.removelast();
  }
  /**
   * 栈顶元素
   * @return
   */
  public string top() {
   return stacklist.getlast();
  }
  /**
   * 栈是否为空
   * @return
   */
  public boolean isempty() {
   return stacklist.isempty();
  }
 }
}

以上这篇java代码执行字符串中的逻辑运算方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

上一篇:

下一篇: