方式一
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