java代码执行字符串中的逻辑运算方法
方式一
publicclassTest { publicstaticvoidmain(String[]args)throwsException{ Stringstr="(aorb)andc"; str=str.replaceAll("or","||"); str=str.replaceAll("and","&&"); System.out.println(str); ScriptEngineManagermanager=newScriptEngineManager(); ScriptEngineengine=manager.getEngineByName("js"); engine.put("a",true); engine.put("b",false); engine.put("c",true); Objectresult=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:2011coffeesweetInc.Allrightsreserved. */ packageorg.coffeesweet.util; importjava.math.BigDecimal; importjava.math.MathContext; importjava.math.RoundingMode; importjava.util.ArrayList; importjava.util.LinkedList; importjava.util.List; importjava.util.StringTokenizer; importjava.util.regex.Matcher; importjava.util.regex.Pattern; /** *@authorcoffeesweet *+,-,*,/四则运算的表达式逆波兰解析计算类,精确计算,应用BigDecimal类处理 *支持负数,但规范除整个表达式第一个数为负数时可以不出现在'('后,其它表达式中间任何位置的 *负数必须出现在'('后,即:用括号括起来。比如:-3+(-2+1)*10或-3+((-2)+1)*10或(-3)+(-2+1)*10或(-3)+((-2)+1)*10 */ publicclassMathExpress{ /** *+ */ privatefinalstaticStringOP1="+"; /** *- */ privatefinalstaticStringOP2="-"; /** ** */ privatefinalstaticStringOP3="*"; /** */ */ privatefinalstaticStringOP4="/"; /** *^ */ //privatefinalstaticStringOP5="^"; /** *% */ //privatefinalstaticStringOP6="%"; /** *( */ privatefinalstaticStringOPSTART="("; /** *) */ privatefinalstaticStringOPEND=")"; /** *!用来替代负数前面的'-' */ //privatefinalstaticStringNEGATIVESING="!"; /** *!用来替代负数前面的'+' */ //privatefinalstaticStringPLUSSING="@"; /** *'#'用来代表运算级别最低的特殊字符 */ //privatefinalstaticStringLOWESTSING="#"; //最原始的四则运算式 privateStringexpBase; //经过初始化处理后的四则运算式 privateStringexpInited; //精度 privateintprecision=10; //取舍模式 privateRoundingModeroundingMode=RoundingMode.HALF_UP; //精度上下文 privateMathContextmc; //四则运算解析 privateListexpList=newArrayList (); //存放逆波兰表达式 privateList rpnList=newArrayList (); publicMathExpress(){ } publicMathExpress(StringexpBase){ init(expBase,this.precision,this.roundingMode); } publicMathExpress(StringexpBase,intprecision,RoundingModeroundingMode){ init(expBase,precision,roundingMode); } publicvoidinit(StringexpBase,intprecision,RoundingModeroundingMode){ this.expBase=expBase; this.precision=precision; this.roundingMode=roundingMode; this.mc=newMathContext(precision,roundingMode); this.expInited=initExpress(expBase); StringTokenizerst=newStringTokenizer(this.expInited,"+-*/^%()",true); while(st.hasMoreElements()){ this.expList.add(st.nextElement().toString().trim()); } this.rpnList=initRPN(this.expList); } /** *@returntheexpBase */ publicStringgetExpBase(){ returnexpBase; } /** *@paramexpBasetheexpBasetoset */ publicvoidsetExpBase(StringexpBase){ this.expBase=expBase; } /** *@returntheexpInited */ publicStringgetExpInited(){ returnexpInited; } /** *@paramexpInitedtheexpInitedtoset */ publicvoidsetExpInited(StringexpInited){ this.expInited=expInited; } /** *@returntheprecision */ publicintgetPrecision(){ returnprecision; } /** *@paramprecisiontheprecisiontoset */ publicvoidsetPrecision(intprecision){ this.precision=precision; } /** *@returntheroundingMode */ publicRoundingModegetRoundingMode(){ returnroundingMode; } /** *@paramroundingModetheroundingModetoset */ publicvoidsetRoundingMode(RoundingModeroundingMode){ this.roundingMode=roundingMode; } /** *@returntheexpList */ publicList getExpList(){ returnexpList; } /** *@paramexpListtheexpListtoset */ publicvoidsetExpList(List expList){ this.expList=expList; } /** *@returntherpnList */ publicList getRpnList(){ returnrpnList; } /** *@paramrpnListtherpnListtoset */ publicvoidsetRpnList(List rpnList){ this.rpnList=rpnList; } /** *@returnthemc */ publicMathContextgetMc(){ returnmc; } /** *@parammcthemctoset */ publicvoidsetMc(MathContextmc){ this.mc=mc; } /** *去除空白字符和在负号'-'前加'0',便于后面的StringTokenizer *@paramexp *@return */ privatestaticStringinitExpress(Stringexp){ StringreStr=null; reStr=exp.replaceAll("\\s",""); if(reStr.startsWith("-")){ reStr="0"+reStr; } reStr=reStr.replaceAll("\\(\\-","(0-"); returnreStr; } /** *是否是整数或是浮点数,但默认-05.15这种也认为是正确的格式 *@paramstr *@return */ privatebooleanisNumber(Stringstr){ Patternp=Pattern.compile("^(-?\\d+)(\\.\\d+)?$"); Matcherm=p.matcher(str); booleanisNumber=m.matches(); returnisNumber; } /** *设置优先级顺序()设置与否无所谓 *@paramsign *@return */ privateintprecedence(Stringstr){ charsign=str.charAt(0); switch(sign){ case'+': case'-': return1; case'*': case'/': return2; case'^': case'%': return3; case'(': case')': //case'#': default: return0; } } /** *转变为逆波兰表达式 *@paramstrList *@return */ publicList initRPN(List strList){ List returnList=newArrayList (); //用来存放操作符的栈 Stackstack=newStack(); //stack.push(LOWESTSING); intlength=strList.size(); for(inti=0;i =precedence(str)){ //如果栈顶元素优先级大于当前元素优先级则 while(!stack.isEmpty()&&precedence(stack.top())>=precedence(str)){ returnList.add(stack.pop()); } } stack.push(str); } } } } //如果栈不为空,则将栈中所有元素出栈放到逆波兰链表的最后 while(!stack.isEmpty()){ returnList.add(stack.pop()); } returnreturnList; } /** *计算逆波兰表达式 *@paramrpnList *@return */ publicStringcaculate(List rpnList){ StacknumberStack=newStack(); intlength=rpnList.size(); for(inti=0;i 2""1<5""1==5""1!=5""(1.0+2)>3""((-0.9+3)>=2.1)" *不支持&&,||等连接符 *@paramstr *@return */ publicstaticbooleancompareTo(StringstrParm){ booleanreBoolean=false; booleanisParentheses=false;//标记是否有()括上整个字符串 Stringstr=initExpress(strParm); Patternp=Pattern.compile("^\\([\\s\\S]*\\)$"); Matcherm=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("<")) thrownewIllegalArgumentException("异常:条件表达式不正确!"); } if(-1!=str.indexOf(">=")){ String[]strTemps=str.split(">="); if(isParentheses){ strTemps[0]=strTemps[0]+")"; strTemps[1]="("+strTemps[1]; } intr=newBigDecimal((newMathExpress(strTemps[0]).caculate())).compareTo(newBigDecimal((newMathExpress(strTemps[1]).caculate()))); if(-1==r){ reBoolean=false; }else{ reBoolean=true; } }elseif(-1!=str.indexOf("<=")){ String[]strTemps=str.split("<="); if(isParentheses){ strTemps[0]=strTemps[0]+")"; strTemps[1]="("+strTemps[1]; } intr=newBigDecimal((newMathExpress(strTemps[0]).caculate())).compareTo(newBigDecimal((newMathExpress(strTemps[1]).caculate()))); if(1==r){ reBoolean=false; }else{ reBoolean=true; } }elseif(-1!=str.indexOf("==")){ String[]strTemps=str.split("=="); if(isParentheses){ strTemps[0]=strTemps[0]+")"; strTemps[1]="("+strTemps[1]; } intr=newBigDecimal((newMathExpress(strTemps[0]).caculate())).compareTo(newBigDecimal((newMathExpress(strTemps[1]).caculate()))); if(0==r){ reBoolean=true; }else{ reBoolean=false; } }elseif(-1!=str.indexOf("!=")){ String[]strTemps=str.split("!="); if(isParentheses){ strTemps[0]=strTemps[0]+")"; strTemps[1]="("+strTemps[1]; } intr=newBigDecimal((newMathExpress(strTemps[0]).caculate())).compareTo(newBigDecimal((newMathExpress(strTemps[1]).caculate()))); if(0!=r){ reBoolean=true; }else{ reBoolean=false; } }elseif((-1!=str.indexOf(">"))&&(-1==str.indexOf("="))){ String[]strTemps=str.split(">"); if(isParentheses){ strTemps[0]=strTemps[0]+")"; strTemps[1]="("+strTemps[1]; } intr=newBigDecimal((newMathExpress(strTemps[0]).caculate())).compareTo(newBigDecimal((newMathExpress(strTemps[1]).caculate()))); if(1==r){ reBoolean=true; }else{ reBoolean=false; } }elseif((-1!=str.indexOf("<"))&&(-1==str.indexOf("="))){ String[]strTemps=str.split("<"); if(isParentheses){ strTemps[0]=strTemps[0]+")"; strTemps[1]="("+strTemps[1]; } intr=newBigDecimal((newMathExpress(strTemps[0]).caculate())).compareTo(newBigDecimal((newMathExpress(strTemps[1]).caculate()))); if(-1==r){ reBoolean=true; }else{ reBoolean=false; } } returnreBoolean; } publicstaticvoidmain(String...args){ //MathExpressme=newMathExpress("-(-0.5+0.1)*10+2",10,RoundingMode.HALF_UP); //System.out.println(me.getExpList()); //List tempList=me.initRPN(me.getExpList()); //System.out.println(tempList); //StringresultStr=me.caculate(tempList); //System.out.println(resultStr); MathExpressme=newMathExpress("-(-1.5000000003+0.1)*10+2"); StringresultStr=me.caculate(); BigDecimalbd=newBigDecimal(resultStr); BigDecimalbd2=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("------------------------------------"); //Patternp=Pattern.compile("^\\([\\s\\S]*\\)$");//匹配类似以'('开头')'结尾的字符串 //Matcherm=p.matcher("(2.0>2.22)"); //System.out.println(m.matches()); booleanreBoolean=MathExpress.compareTo("((-8.0+3)>=2.1)"); System.out.println(reBoolean); } /** *栈 */ privateclassStack{ LinkedList stackList=newLinkedList (); publicStack(){ } /** *入栈 *@paramexpression */ publicvoidpush(Stringexpression){ stackList.addLast(expression); } /** *出栈 *@return */ publicStringpop(){ returnstackList.removeLast(); } /** *栈顶元素 *@return */ publicStringtop(){ returnstackList.getLast(); } /** *栈是否为空 *@return */ publicbooleanisEmpty(){ returnstackList.isEmpty(); } } }
以上这篇java代码执行字符串中的逻辑运算方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。