什么是中序表達式
前序(前綴)表達式要求每一個操作符出現在其操作數之前.一般不用. 寫表達式的后序表達式一般是為了便利于計算機編程中棧的實現,所以用的較多.
具體代碼如下所示:
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 表達式求值; import java.util.stack; /* * 中序表達式求值實現 */ public class centerexpression { public double evaluate(string expression){ //傳入中序表達式 char [] ex = expression.tochararray(); stack< double > num = new stack<>(); stack<character> ops = new stack<>(); for ( int i = 0 ; i < ex.length; i++){ //循環將表達式依次入棧 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()){ //處理剩余可以按計算機掃描順序處理的表達式 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" )); } } |
總結
以上所述是小編給大家介紹的java實現中序表達式的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:https://www.cnblogs.com/libin-blogs/archive/2018/08/08/9441231.html