2015-10-18 258 views
0

如何將此代碼中的字符轉換爲字符串? InfixToPostfix必須能夠接受字符串而不是字符,因此它可以接受兩位數字和空格。有什麼建議麼?提前致謝。InfixToPostfix將字符轉換爲字符串

import java.util.Stack; 

public class InfixToPostfix 
{ 
private Stack operators = new Stack(); 

public InfixToPostfix() 
{ 

} 

public String toPostfix(String infix) 
{ 
    char[] characters = new char[100]; 
    int i; 
    int length = infix.length(); 
    infix.getChars(0, length, characters, 0); 
    char operator; 
    String output = ""; 

    for (i = 0; i < length; i++) 
    { 
     if (isOperator(characters[i])) 
      if (operators.empty()) 

       operators.push(characters[i]); 
      else 
      { 
       if (operatorLessPrecedence(characters[i])) 

       { 
        do 
        { 
         output = output + operators.pop(); 
        } 
        while (!operators.empty() && operatorLessPrecedence(characters[i])); 
        operators.push(characters[i]); 
       } 
       else 

        operators.push(characters[i]); 
      } 
     else 

      output = output + characters[i]; 
    } 
    while (!operators.empty()) 
    { 

     operator = (char)operators.pop(); 
     output = output + operator; 
    } 
    return output; 
} 

/** 
* operator 
*/ 

public boolean isOperator(char c) 
{ 
    if (c == '*' || 
     c == '/' || 
     c == '+' || 
     c == '^' || 
     c == '-') 
     return true; 
    else 
     return false; 
} 


public boolean operatorLessPrecedence(char o) 
{ 
    int operatorPrecedence = precedence(o); 
    int tosPrecedence = precedence((char)operators.peek()); 
    return (operatorPrecedence <= tosPrecedence); 
} 

/** 
* precedence 
*/ 
public int precedence(char o) 
{ 
    switch (o) 
    { 
     case '+': return 1; 
     case '-': return 1; 
     case '*': return 2; 
     case '/': return 2; 
     case '^': return 3; 
    } 
    return 5; 
} 

}

回答

0

我將與其將輸入到令牌集合的詞法分析階段的代碼分割成兩個。然後這些傳遞給分流碼算法,該算法使用一組令牌。在lexing階段,您可以使用正則表達式來檢測不同類型的輸入。說/ \ d + /檢測一個或多個數字的序列。