2017-10-13 46 views
0

我有可以從它的中綴表示法轉換表達式來其後綴表示法的方法,但我不知道如何處理的數字大於9具有> 1位數

例如更大的轉換中綴爲後綴, 如果我有12-(5 + 3),我不希望它被表示爲1253 + - 而是12 53 + - (或類似的形式)。

我有什麼:

private void postfix(){ 
     String result = ""; 
     LinkedStack<Character> stack = new LinkedStack<Character>(); 
     for (int i = 0; i < expression.length(); i++){ 
      char c = expression.charAt(i); 
      if (Character.isDigit(c)){ 
        result += c; 
      } 
      else if (c == '('){ 
        stack.push(c); 
      } 
      else if (c == ')'){ 
        while (!stack.isEmpty() && stack.peek() != '('){ 
         result += stack.pop(); 
        } 
        if (!stack.isEmpty() && stack.peek() != '('){ 
         result = "Invalid Expression"; 
        } 
        else{ 
         stack.pop(); 
        } 
       } 
      else if(isOperator(c)){ 
       while (!stack.isEmpty() && weight(c) <= weight(stack.peek())) 
         result += stack.pop(); 
       stack.push(c); 
      } 
     } 
     postfixed = result; 
    } 

回答

1

您需要修改這部分代碼:如果表達式爲 「1234」

if (Character.isDigit(c)){ 
    result += c; 
} 

,你只計算1 + 2 + 3 +4而不是將1234當作單一數字。

你可以做的是將連續的數字收集到String。然後,將字符串轉換爲整數使用Integer.parseInt()