什么是中序表達(dá)式
前序(前綴)表達(dá)式要求每一個(gè)操作符出現(xiàn)在其操作數(shù)之前.一般不用. 寫表達(dá)式的后序表達(dá)式一般是為了便利于計(jì)算機(jī)編程中棧的實(shí)現(xiàn),所以用的較多.
具體代碼如下所示:
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
|
package 表達(dá)式求值; import java.util.stack; /* * 中序表達(dá)式求值實(shí)現(xiàn) */ public class centerexpression { public double evaluate(string expression){ //傳入中序表達(dá)式 char [] ex = expression.tochararray(); stack< double > num = new stack<>(); stack<character> ops = new stack<>(); for ( int i = 0 ; i < ex.length; i++){ //循環(huán)將表達(dá)式依次入棧 char c = ex[i]; if (c < '9' && c > '0' ){ num.push( double .parsedouble(character.tostring(c))); } else if (c == '(' ){ ops.push( '(' ); } else if (c == ')' ){ while ( true ){ char op = ops.pop(); if (op == '(' ){ break ; } else { switch (op){ case '+' :num.push(num.pop()+num.pop()); break ; case '-' :num.push(num.pop()-num.pop()); break ; case '*' :num.push(num.pop()*num.pop()); break ; case '/' :num.push(num.pop()/num.pop()); break ; default : break ; } } } } else if (ops.empty() && (c == '+' || c == '-' || c == '*' || c == '/' )){ ops.push(c); } else if (!ops.isempty() && (c == '+' || c == '-' || c == '*' || c == '/' )){ char op =ops.peek(); while ((op == '*' || op == '/' ) && (c == '+' || c == '-' )){ op = ops.pop(); switch (op){ case '+' :num.push(num.pop()+num.pop()); break ; case '-' :num.push(num.pop()-num.pop()); break ; case '*' :num.push(num.pop()*num.pop()); break ; case '/' :num.push(num.pop()/num.pop()); break ; default : break ; } if (ops.isempty()){ break ; } else { op = ops.peek(); } } ops.push(c); } } while (!ops.isempty()){ //處理剩余可以按計(jì)算機(jī)掃描順序處理的表達(dá)式 char op =ops.pop(); switch (op){ case '+' :num.push(num.pop()+num.pop()); break ; case '-' :num.push(num.pop()-num.pop()); break ; case '*' :num.push(num.pop()*num.pop()); break ; case '/' :num.push(num.pop()/num.pop()); break ; default : break ; } } return num.pop(); } public static void main(string [] args){ centerexpression exp = new centerexpression(); system.out.println(exp.evaluate( "1*2+5*3" )); } } |
總結(jié)
以上所述是小編給大家介紹的java實(shí)現(xiàn)中序表達(dá)式的實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)服務(wù)器之家網(wǎng)站的支持!
原文鏈接:https://www.cnblogs.com/libin-blogs/archive/2018/08/08/9441231.html