方式一
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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类型的四则运算时结果会出现循环小数,运算结果会出现问题.
方式二(能够保证四则运算精度):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 |
/** * @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代码执行字符串中的逻辑运算方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
原文链接:https://blog.csdn.net/qq_27739989/article/details/72551029
查看更多关于java代码执行字符串中的逻辑运算方法的详细内容...