1. 程式人生 > >java實現中綴表達式轉後綴表達式

java實現中綴表達式轉後綴表達式

exce left align pex ava pre div 表達 logs

技術分享
 1 package postfix;
 2 
 3 import java.util.Stack;
 4 
 5 /**
 6  * 
 7  * @author DELL 將中綴表達式轉化為後綴表達式
 8  */
 9 
10 public class Expression {
11     private StringBuffer iExp; // 存儲中綴表達式
12     private Stack stack;
13     private StringBuffer pExp; // 存儲後綴表達式
14 
15     public Expression(String s) {
16         iExp = new
StringBuffer(s); 17 stack = new Stack(); 18 pExp = new StringBuffer(); 19 } 20 21 public String toPostfix() throws Exception { 22 while (iExp.length() != 0) { 23 char c = iExp.charAt(0); 24 iExp.deleteCharAt(0); 25 switch (c) { 26 case
‘0‘: 27 case ‘1‘: 28 case ‘2‘: 29 case ‘3‘: 30 case ‘4‘: 31 case ‘5‘: 32 case ‘6‘: 33 case ‘7‘: 34 case ‘8‘: 35 case ‘9‘: 36 pExp.append(c); 37 break; 38 case
‘(‘: 39 stack.push(c); 40 break; 41 case ‘)‘: 42 while (stack.peek() != (Object) ‘(‘) { 43 pExp.append(stack.pop()); 44 } 45 stack.pop(); 46 break; 47 case ‘+‘: 48 case ‘-‘: 49 while (!stack.isEmpty() && stack.peek() != (Object) ‘(‘) { 50 pExp.append(stack.pop()); 51 } 52 stack.push(c); 53 54 break; 55 case ‘*‘: 56 case ‘/‘: 57 while (!stack.isEmpty() && stack.peek() != (Object) ‘(‘ && stack.peek() != (Object) ‘+‘ 58 && stack.peek() != (Object) ‘-‘) { 59 pExp.append(stack.pop()); 60 } 61 stack.push(c); 62 break; 63 case ‘^‘: 64 stack.push(‘^‘); 65 break; 66 default: 67 System.out.println("出現錯誤字符"+c); 68 break; 69 } 70 71 } 72 while (!stack.isEmpty()) { 73 pExp.append(stack.pop()); 74 } 75 return pExp.toString(); 76 } 77 78 }
View Code

撰寫時間:2017-08-13 16:50:11

修改時間:

java實現中綴表達式轉後綴表達式