Postfix to infix

Can someone please help. I am a little confused on how to convert an infix expression (ex. ab*cde/-+) to a postfix expression (ex. a*b+(c-d/e)). I don't expect you to write the code for me, although that would be nice, I just need to understand the logic behind this.
Thanks,
Tiffanee

Here is what I have. there is an error when reading in token by token. if I type as a postfix epr. 12+ it outputs
(0 + 12). For some reason 12 instead of 1 as the first token. I don't know whats wrong.
public class InfixParser {
static final int END = 0, VALUE = 1, LPAREN = 2, RPAREN = 3, EXP = 4, MULT = 5, DIV = 6, PLUS = 7, MINUS = 8;
private StringTokenizer str;
private String curValue;
private Stack infix;
private String infixValue; //the infix representation of a operation
public String getInfixValue()
return infixValue;
//constructor
public InfixParser(String s)
infix = new StackAr();
str = new StringTokenizer(s, "+-*/^() ", true);
infix.push(new Integer(END));
//converts from Postfix form to Infix form
public void toInfix () {
int newToken=0;
try {
do {
newToken = getToken(); //get the next token in the string
switch(newToken) {
//if the token is a variable or number, push onto infix stack
case VALUE:
System.out.println("curValue: "+curValue);
infix.push(curValue);
break;
case LPAREN:
String a="(-";
newToken = getToken();
//if the value inside the ( is positive, push onto stack
if (newToken != MINUS) {
a="("+curValue+")";
infix.push(a);
break;
//if the value is negative, push the negative onto stack
newToken = getToken();
a= a + curValue + ")";
infix.push(a);
break;
//if it is end of string, infixValue is the top of the stack
case END:
infixValue=(String)infix.top();
break;
case RPAREN:
break;
//if it is an operator, pop the top two objects from stack,
//put the toString form of the operator between them, and push
//back onto stack
case EXP:
case DIV:
case MULT:
case PLUS:
case MINUS:
Object var1=infix.topAndPop();
Object var2=infix.topAndPop();
infixValue="("+var2+" "+enumToString(newToken)+" "+var1+")";
infix.push(infixValue);
break;
default:
System.out.println("ERROR: Invalid Token" + newToken);
} while (newToken != END);
catch (Exception e)
System.out.println("ERROR: " + e);
//the string representation of the different operators
private String enumToString(int op) {
switch(op) {
case EXP: return "^";
case DIV: return "/";
case MULT:return "*";
case PLUS:
return "+";
case MINUS:
return "-";
case END:
return "";
default:
return "?";
//get the next token in the string
private int getToken() {
String s = "";
try
s= str.nextToken();
catch(java.util.NoSuchElementException e) {
return END;
if(s.equals(" ")) {
return getToken();
if(s.equals("^")) {
return EXP;
if(s.equals("/")) {
return DIV;
if(s.equals("*")) {
return MULT;
if(s.equals("(")) {
return LPAREN ;
if(s.equals(")")) {
return RPAREN;
if(s.equals("+")) {
return PLUS;
if(s.equals("-")) {
return MINUS ;
//if the token is none of the above, it must be a variable or number
//so the curVal becomes whatever the token is and VALUE is returned
curValue = s;
return VALUE;
//main method used to test InfixParser by itself
public static void main(String[] args) {
String str = "";
String quit = "q";
BufferedReader in = new BufferedReader (new
InputStreamReader(System.in));
try {
while (str.compareTo(quit) != 0) {
System.out.print("Enter Postfix expression or q to Exit: ");
if ((str = in.readLine()) == null) {
break;
System.out.print("Expression: " + str + "\n");
InfixParser par = new InfixParser(str);
par.toInfix();
System.out.print("InFix Expression: "+par.infixValue);
System.out.println();
catch (IOException e) {
System.out.println("ERROR" + e);

Similar Messages

  • Creating a PostFix Expression!

    Hi guys I've been working in this project all day and I still can't really come up with a solution.
    What I'm doing is allowing the user to enter a infix expression such as a + b * c and an output with the postfix expression should appear in this order.
    A - Will go to a string
    + To Stack
    B To String
    * To Stack
    Then With a presedence method I should be able to determine if which operator has a higher value.
    Output Should look like:
    abc * +
    Here is my code so far I will appreciate some help or advice. Thank you
    import java.util.*;
    class Expression
         private String inFixString;
         private String postFixString;
         private String stringToken;
         public Expression()
             inFixString = "";
              postFixString = "";
         public void getInfix(String inFix)
              inFixString = inFix;               
         public void showInfix()
              System.out.println("This is the In Fix Expression : ");
              System.out.println(inFixString);
         public void showPostFix()
              System.out.println(postFixString);
         public void convertToPostFix()
              //Parsing out the string store in InFixString.
              StringTokenizer tokenizeString = new StringTokenizer(inFixString);
              Stack putInFixInStack = new Stack();
              boolean status = tokenizeString.hasMoreTokens();
              boolean stackStatus = putInFixInStack.isEmpty();
              String currentOp = "";
              while(tokenizeString.hasMoreTokens())
                   stringToken = tokenizeString.nextToken();
                   //Reading Current Token if is a letter add it to postFix Expression
                   if (Character.isLetter(stringToken.charAt(0)))
                        postFixString += stringToken;     System.out.println("Number : " + stringToken + " was appended to Post Fix");    
                  }//ABC          [     *+]
                  switch (stringToken.charAt(0))//   A + B  * C   post  AB + C -  |||||||||||||||||  GETTING ABC -+
                        case '(': System.out.println("( " + " was Push into Stack");
                             putInFixInStack.push("(");
                        break;
                        case ')':System.out.println(")" + " was Push into Stack");
                             putInFixInStack.push(")");
                        break;
                        case '+':
                             if (putInFixInStack.isEmpty())
                                  putInFixInStack.push("+");
                                  System.out.println("+" + " was Push into Stack");          
                             else
                                  putInFixInStack.push("+");
                                  System.out.println("+" + " was Push into Stack");
                                  while(stackStatus)
                                           currentOp = putInFixInStack.peek().toString();
                                       if (precedence(currentOp.charAt(0)) == 1)
                                            putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 2)
                                            putInFixInStack.pop();
                                            postFixString += currentOp;
                                       else if (precedence(currentOp.charAt(0)) == 3)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 4)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       else
                                       stackStatus = putInFixInStack.isEmpty();
                        break;
                        case '-':
                             if (putInFixInStack.isEmpty())
                                  putInFixInStack.push("-");
                                  System.out.println("-" + " was Push into Stack");
                             else
                                  putInFixInStack.push("-");
                                  System.out.println("-" + " was Push into Stack");
                                  while(stackStatus)
                                           currentOp = putInFixInStack.peek().toString();
                                       if (precedence(currentOp.charAt(0)) == 1)
                                       putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 2)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 3)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 4)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       stackStatus = putInFixInStack.isEmpty();
                        break;
                        case '*':
                             if (putInFixInStack.isEmpty())
                                  putInFixInStack.push("*");
                                  System.out.println("*" + " was Push into Stack");
                             else
                                  putInFixInStack.push("*");
                                  System.out.println("*" + " was Push into Stack");
                                  while(stackStatus)
                                           currentOp = putInFixInStack.peek().toString();
                                       if (precedence(currentOp.charAt(0)) == 1)
                                            putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 2)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 3)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       else if (precedence(currentOp.charAt(0)) == 4)
                                            postFixString += currentOp;
                                            putInFixInStack.pop();
                                       stackStatus = putInFixInStack.isEmpty();
                        break;
                        case '/':System.out.println("/" + " was Push into Stack");
                             putInFixInStack.push("/");
                        break; default:
              postFixString += putInFixInStack.peek().toString();
              stackStatus = putInFixInStack.isEmpty();
              System.out.println();
              System.out.println("Post Fix Has : " + postFixString);
         private int precedence(char in)
            switch(in)
                  case '/':
                       return 5;
                  case '*':
                     return 4;
                case '+':
                        return 3;
                case '-':
                    return 2;
                case '(': case ')':
                    return 1;
              return 0;
        public boolean isOperator()
             String[] operators = { "+" , "-" , "/" , "*" , "(" , ")" };
             boolean isOp = false;
             for( int i  = 0; i < operators.length;i++)
                  if (operators[i] == "+" )
                  isOp = true;
                  else if (operators[i] == "-" )
                  isOp = true;
                  else if (operators[i] == "/" )
                  isOp = true;
                  else if (operators[i] == "*" )
                  isOp = true;              
                  else if (operators[i] == "(")
                  isOp = true;
                  else if (operators[i] == ")" )
                  isOp = true;
                  else
                  isOp = false;
             return isOp;
         public  boolean equals(String otherElement)
              // If Current Token == Other Element return true otherwise False
              if (stringToken == otherElement)
              return true;
              else
              return false;
    }

    Here is the another java program
    which implements same algorithm & it works!!!
    Hope that it helps.
    I have run your program but it does not print anything!!!
    So I wrote my own!!!!
    //By Prafulla V Tekawade
    //[email protected]
    import java.util.*;
    class MyExpression
         public String inFix;
         public String postFix;
         public MyExpression(String str)
              inFix="("+str+")";
              postFix="";
         public void convert()
              Stack opstk=new Stack();
              int m=inFix.length();
              int i;
              for(i=0;i<m;i++)
                   if(!isOperator(inFix.charAt(i)))
                        if(inFix.charAt(i)!=')')
                             postFix += inFix.charAt(i);
                   if(inFix.charAt(i) == '(')
                        opstk.push(inFix.charAt(i));
                   if(isOperator(inFix.charAt(i)))
                        if(opstk.isEmpty())
                             while(getPriority((Character)opstk.peek()) >= getPriority(inFix.charAt(i)))
                                  postFix += opstk.pop();
                        opstk.push(inFix.charAt(i));
                   if(inFix.charAt(i) == ')')
                        char ch=(Character)opstk.pop();
                        while((ch != '(') && (!opstk.isEmpty()))
                             postFix += ch;
                             ch=(Character)opstk.pop();
              while((!opstk.isEmpty()))
                   char ch=(Character)opstk.pop();
                   if(ch!='(')
                        postFix += ch;
         public boolean isOperator(char ch)
              switch(ch)
                   case '+':
                   case '-':
                   case '/':
                   case '*':
                   case '(':
                             return true;
                   default:
                             return false;
         public int getPriority(char ch)
              switch(ch)
                   case '(':
                             return 0;
                   case '+':
                   case '-':
                             return 1;
                   case '*':
                   case '/':
                   case '%':
                             return 2;
              return -1;
         public void printPostFix()
              System.out.println (postFix);
         public static void main(String []args)
              MyExpression obj=new MyExpression("(a+b)*c");
              obj.convert();
              obj.printPostFix();
    Output
    Infix     := a+b*c
    PostFix     := abc*+
    Infix      := (a+b)*c
    PostFix := ab+c*
    Infix:=  (a+((b*c+(p*q)))+(a+(b-c)))+(d+w)+(d*q)
    PostFix= abcpq*+*abc-+dw+dq*++++
    */

  • Any Suggestions?

    I know you have seen tons of these questions from students, but mine is a bit different. I am not asking how to do the convertions, I am asking how to remove parens. I have partically done some of the paren removal, but as you can see from my output below, I still have a spare in locations that really don't need them. I am wondering if I need to do a second run through the expression and "strip" parens or not.
    Any ideas, suggestions or hints would be greatly appreciated.
    Infix and Postfix Expressions
    Author: C. K. Bales
    Copyright 2002
    Starting Infix to Postfix Expressions:
    Infix Expression: (A+C)*D
    Postfix Expression: AC+D*
    Infix Expression: A+C*D
    Postfix Expression: ACD*+
    Infix Expression: Z+D-F*G
    Postfix Expression: ZD+FG*-
    Infix Expression: (Z+D-F)*G
    Postfix Expression: ZD+F-G*
    Infix Expression: A^3*B^2*C^1
    Postfix Expression: A3^B2^*C1^*
    Infix Expression: A-B^C
    Postfix Expression: ABC^-
    Starting Postfix to Infix Expressions:
    Postfix Expression: XYZ+*
    Infix Expression: X*Y+Z
    Postfix Expression: KJ*L/
    Infix Expression: (K*J)/L
    Postfix Expression: ACD*+
    Infix Expression: A+C*D
    Postfix Expression: ZD+F-G*
    Infix Expression: ((Z+D)-F)*G
    End of Expressions in File.
    Thank you for using our software.
    The two that I would like to strip the parens from are (K*J)/L and ((Z+D)-F)*G.
    They should read K*J/L and (Z+D-F)*G.
    The code that currently handles removing the parens is:
    if (!stack.isEmpty() && isOperand(temp.toString())) {
    x = (String)stack.pop();
    y = (String)stack.pop();
    together = "(" + y + postfix + x + ")";
    infix += together;
    infixExpr = infix;
    together = "";
    infix = "";
    } else {
    x = (String)stack.pop();
    y = (String)stack.pop();
    together = y + postfix + x;
    infix += together;
    infixExpr = infix;
    together = "";
    infix = "";
    } //end if
    stack.push(infixExpr);
    Should I run a deeper check than that? I really don't want to make it more complicated than it needs to be...like I said, any ideas, suggestions, hints would be greatly appreciated...thanks!
    CK

    Let's see if I get this right. I am currently taking the Data Structures class and Big(O) and I have not been getting along terribly well. I am serverly dyslexic and the Data Structures text book uses very long and complicated string computations to result in the Big(O) notation. I have re-read those chapters several times to try to get it down for the final.
    Ok, ACIDS is the mechinism used to test which ADT is best to use:
    Add
    Change
    Inspect
    Delete
    Sort
    Arrays -
    They have a fixed size and give the programmer the advantage of the [] sub-brackets to access data items within the array.
    To insert it is n-1 moves
    To delete it is n-1 moves
    To insert in order it is n-1 moves
    And you can go straight to any point in the array.
    Current sort algorithms work with an array
    Linked Lists -
    Insert at front of list is n
    Delete from front of list is n
    Dynamic size
    Add in order is n links
    Delete a specific link is n links
    Current sort algorithms don't work with a Linked List
    Big(O) of a Linked List is on most cases n
    Big(O) of an Array on most cases is n^2.
    When is it best to use one over the other?
    If there will not be a lot of changes done to the data, and you need instant access to each element of data, use an array.
    If there will be a great many changes done to the data, and instant access isn't overtly necessary, use a Linked List.
    Which uses less memory as they "increase". To increase an Array you must create a new array and copy the old one into it. Such things as ArrayLists automatically double the size of the array as you add new elements to it. Both use a lot of overhead in maintaining a contiguious segment of memory to hold the information within them.
    A Linked List doesn't need contiguious memory, and only increases by one each time a link is added, therefore it doesn't use a lot of memory.
    Both can be fast for small amounts of data, but over time, a Linked List will be faster than an array with extremely large amounts of data.
    Though I may be wrong on the Big(O) part, I have been reading my homework and have gotten full points on my other three assignments in this class so far.
    <g>
    Thanks, that was fun!
    CK

  • Traversing a binary tree

    Hi
    I've written the following code for converting Postfix to Infix,it reads a string then reads it letter by letter ,a stack and a Tree is used,and I want to traverse the last object that has poped from the stack,in the following code I used this line:
    System.out.println((Character)(((TreeNode)stack.pop()).data));
    but it only prints the root of the tree,I tried to traverse it but I don't have any idea,I did sth like this( for traversing another node):
    (TreeNode)stack.pop() = ( (TreeNode)stack.pop() ).data;
    System.out.println((Character)(((TreeNode)stack.pop()).data));
    but it didn't work.
    would you plz help me with it.
    Here is the code:
    import java.util.Scanner;
    public class Test
    public static void main( String args[])
    Scanner input = new Scanner( System.in );
    System.out.printf("Enter your String(in Postfix):\n");
    String c = input.nextLine();//read a line of text
    Stack stack = new Stack();
    int i = 0 ;
    while( i < c.length() )
    char a = c.charAt( i );
    if( Character.isLetterOrDigit (a) )
    System.out.printf("\n%c" , a );
    stack.push( new TreeNode( a ) );
    else if( a == '+' || a == '-' || a == '*' || a == '/' )
    TreeNode t = new TreeNode( a );
    t.insert( 0 , stack.pop() );
    t.insert( 1 , stack.pop() );
    stack.push( t );
    i++;
    (TreeNode)stack.pop() = ( (TreeNode)stack.pop() ).data; //<-----Here is the problem
    System.out.println((Character)(((TreeNode)stack.pop()).data));
    Thax
    Bita

    Well, two things. First, you're trying to assign to a method call, which isn't valid. The compiler probably told you this.
    Second, you're popping things from the stack more often than you need to (e.g., for printing) so the stack probably won't be in the state you need.
    When you post code, please wrap it in code tags so it'll be legible. Highlight it and then click the CODE button above the text input box.

  • Logical infix expression to postfix error

    Hi,
    I've got a program which takes input at command line as an infix expressions and then aims to convert it to postfix for later evaluation . I carry this out using two stacks. My coding for this to happen is below( only parts i felt needed):
    private String postfix = "";
        private static Stack<Character> operatorStack = new Stack<Character>();
        private static Stack<Character> operandStack = new Stack<Character>();
                userEntry.trim();
                char[] temp = userEntry.toCharArray();
                for (int i = 0 ; i < temp.length ; i++) {
                    char a = temp;
    System.out.println(a);
    dump(temp);
    if(userEntry.startsWith("end")) {
    finished = true;
    System.out.println("Thank You for using Calculator");
    * dump. Places the input into a char array and push each
    * char to stack.
    * @param temp array of strings to be tokenized and
    * pushed ontop of stack
    private void dump(char[] temp)
    for(char c : temp) {
    Character C = new Character(c);
    String token;
    token = C.toString();
    System.out.println("Testing token "+token);
    //its a number just add to the postfix string
    if (Character.isDigit(C)) {
    postfix = postfix + "" + (Integer.parseInt(token));
    System.out.println("new infix"+ postfix);
    //its an operator so push it to operator stack
    else if (token.equals("(")) {
    operatorStack.push(C);
    System.out.println(operatorStack.peek());
    // pop everthing before the ")" until you hit an "(" , this will be the operands
    else if (token.equals(")")) {
    while ((operatorStack.peek()).charValue() != '(') {
    char ch = operatorStack.pop();
    postfix = postfix + " " + ch;
    System.out.println(operatorStack.empty()+"operator stack is empty");
    System.out.println("new postfix 2 "+postfix);
    System.out.println(operatorStack.pop()+"jus kicked somthin off");
    else if (token.equals(" ")){}
    //find the order of operators and put this in to the postfix script, the operators +-,/,- never make it on to the stack
    else {               
    System.out.println(operatorStack.empty()+"operator stack is empty");
    System.out.println(C);
    while (!(operatorStack.empty()) && !((operatorStack.peek()).equals('('))
    && ((setPrecedence(C)) <= (setPrecedence((operatorStack.peek()).charValue())))) {
    System.out.println("precedence test"+operatorStack.peek());
    operatorStack.push(C);
    postfix = postfix + " " + operatorStack.pop();
    System.out.println("just pushed operator");
    while (!operatorStack.empty()) {
    postfix = postfix + " " + operatorStack.pop();
    System.out.println("last postfix :"+postfix);
    public int setPrecedence(char x)
    if (x == '+'|| x == '-') {
    return 1;
    if (x == '*' || x == '/' || x == '%') {
    return 2;
    return 0;
    }if i was to enter at the command line ( 2 + 4 ) * 3 ( must have spaces)
    instead of the postfix conversion being "24+3* it results in "243".
    I've got various print statement in my code but  still can seem to figure out what am doing wrong. I believe the problem lies in my else block of statements.
    Example of entering an expression result :
    ( 2 * 4 ) * 3
    2
    4
    3
    Testing token (
    Testing token 
    Testing token 2
    new infix
    Testing token 
    Testing token *
    falseoperator stack is empty
    Testing token 
    Testing token 4
    new infix24
    Testing token 
    Testing token )
    falseoperator stack is empty
    new postfix 2 24
    (jus kicked somthin off
    Testing token 
    Testing token *
    trueoperator stack is empty
    Testing token 
    Testing token 3
    new infix243
    last postfix :243
    If you can see any reason why its producing this instead of the desired or any thing you disapprove of i would be  greatful if you would kindly say so.
    Thanks alot.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    * CORRECTED CODING INDENTION sorry* hopefully a little clearer.
    Hi,
    I've got a program which takes input at command line as an infix expressions and then aims to convert it to postfix for later evaluation . I carry this out using two stacks. My coding for this to happen is below( only parts i felt needed):
    private String postfix = "";
    private static Stack<Character> operatorStack = new Stack<Character>();
    private static Stack<Character> operandStack = new Stack<Character>();
                userEntry.trim();
                char[] temp = userEntry.toCharArray();
                for (int i = 0 ; i < temp.length ; i++) {
                    char a = temp;
    System.out.println(a);
    dump(temp);
    if (userEntry.startsWith("end")) {
    finished = true;
    System.out.println("Thank You for using Calculator");
    * dump. Places the input into a char array and push each
    * char to stack.
    * @param temp array of strings to be tokenized and
    * pushed ontop of stack
    private void dump(char[] temp)
    for(char c : temp) {
    Character C = new Character(c);
    String token;
    token = C.toString();
    System.out.println("Testing token "+token);
    //its a number just add to the postfix string
    if (Character.isDigit(C)) {
    postfix = postfix + "" + (Integer.parseInt(token));
    System.out.println("new infix"+ postfix);
    //its an operator so push it to operator stack
    else if (token.equals("(")) {
    operatorStack.push(C);
    System.out.println(operatorStack.peek());
    // pop everthing before the ")" until you hit an "(" , this will be the operands
    else if (token.equals(")")) {
    while ((operatorStack.peek()).charValue() != '(') {
    char ch = operatorStack.pop();
    postfix = postfix + " " + ch;
    System.out.println(operatorStack.empty()+"operator stack is empty");
    System.out.println("new postfix 2 "+postfix);
    System.out.println(operatorStack.pop()+"jus kicked somthin off");
    else if (token.equals(" ")) {
    //do nothing
    //find the order of operators and put this in to the postfix script, the operators +-,/,- never make it on to the stack
    else {               
    System.out.println(operatorStack.empty()+"operator stack is empty");
    System.out.println(C);
    while (!(operatorStack.empty()) && !((operatorStack.peek()).equals('('))
    && ((setPrecedence(C)) <= (setPrecedence((operatorStack.peek()).charValue())))) {
    System.out.println("precedence test"+operatorStack.peek());
    operatorStack.push(C);
    postfix = postfix + " " + operatorStack.pop();
    System.out.println("just pushed operator");
    while (!operatorStack.empty()) {
    postfix = postfix + " " + operatorStack.pop();
    System.out.println("last postfix :"+postfix);
    public int setPrecedence(char x)
    if (x == '+'|| x == '-') {
    return 1;
    if (x == '*' || x == '/' || x == '%') {
    return 2;
    return 0;
    }if i was to enter at the command line ( 2 + 4 ) * 3 ( must have spaces)
    instead of the postfix conversion being "24+3* it results in "243".
    I've got various print statement in my code but still can seem to figure out what am doing wrong. I believe the problem lies in my else block of statements.
    Example of entering an expression result :
    ( 2 * 4 ) * 3
    2
    4
    3
    Testing token (
    Testing token
    Testing token 2
    new infix
    Testing token
    Testing token *
    falseoperator stack is empty
    Testing token
    Testing token 4
    new infix24
    Testing token
    Testing token )
    falseoperator stack is empty
    new postfix 2 24
    (jus kicked somthin off
    Testing token
    Testing token *
    trueoperator stack is empty
    Testing token
    Testing token 3
    new infix243
    last postfix :243
    If you can see any reason why its producing this instead of the desired or any thing you disapprove of i would be greatful if you would kindly say so.
    Thanks alot.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • My infix to postfix algorithm

    I need som help to finish my algorithm.
    This is what I have so far:
    import java.util.Stack;
    import javax.swing.*;
    public class InfixToPostfix {
    public static void main(String[] args) {
    Object slutt = "#";
    char[] operator = {'^','*','/','+','-'};
    char vParentes = '(';
    char hParentes = ')';
    char[] uOperator = {'^','*','/','+','-','('};
    char[] opPri = {'^','*','/','+','-','(',')','#'};
    int [] infixPri = { 3 , 2 , 2 , 1 , 1 , 4 , 0 , 0 };
    int [] opStackPri = { 3 , 2 , 2 , 1 , 1 , 0 ,-1 , 0 };
    String infixStr = JOptionPane.showInputDialog("infix : ");
    infixStr += slutt;
    String postfixStr = "";
    System.out.println("Infix: "+infixStr);
    Stack stack = new Stack();
    System.out.println ("Stack is empty: "+stack.empty ());
    char c;
    for (int i=0; i<infixStr.length(); i++) {
    c = infixStr.charAt(i);
    if (c == '+' || c == '-' || c == '*' || c == '/') {
    if (stack.empty()) {
    stack.push(String.valueOf(c));
    else {
    // HELP WANTED!!!!!
    else if (c == '#') {
    System.out.println("Postfix: "+ postfixStr);
    System.exit(0);
    else {
    postfixStr += c;
    In the "help wanted" else-loop I want to do the following:
    The operator from stack should pop, and
    it must be compared with the next operator
    from the infix-expression, in according to the
    priority which is given in the opPri, infixPri and opStackPri.
    The if the infix-operator has a higher priority then I push it
    to the stack, else the stack-operator pops and are added
    to the postfix-string, and the next stack operator is popped and
    compared with the same infix-operator. Then again if the infix has
    a higher value I push it to the stack, else the stack-operator is popped
    and added. So on and so on...
    And it's only supposed to handle one digits numbers.
    As you see, I know how it should function, but I am not sure at all
    about the syntax. Can anyone please help me with this?
    thanks!
    torvald helmer>

    Code tags, please: http://forum.java.sun.com/help.jspa?sec=formatting

  • Infix to postfix algorithm

    I need som help to finish my algoritm.
    This is what I have so far:
    import java.util.Stack;
    import javax.swing.*;
    public class InfixToPostfix {
         public static void main(String[] args) {
              Object slutt      = "#";
              char[] operator      = {'^','*','/','+','-'};
              char vParentes      = '(';
              char hParentes      = ')';
              char[] uOperator      = {'^','*','/','+','-','('};
              char[] opPri      = {'^','*','/','+','-','(',')','#'};
              int [] infixPri      = { 3 , 2 , 2 , 1 , 1 , 4 , 0 , 0 };
              int [] opStackPri      = { 3 , 2 , 2 , 1 , 1 , 0 ,-1 , 0 };
              String infixStr      = JOptionPane.showInputDialog("infix : ");
              infixStr           += slutt;
              String postfixStr     = "";
              System.out.println("Infix: "+infixStr);
              Stack stack = new Stack();
              System.out.println ("Stack is empty: "+stack.empty ());
              char c;
              for (int i=0; i<infixStr.length(); i++) {
                   c = infixStr.charAt(i);
                   if (c == '+' || c == '-' || c == '*' || c == '/') {
                        if (stack.empty()) {
                             stack.push(String.valueOf(c));
                        else {
                             // HELP WANTED!!!!!
                   else if (c == '#') {
                        System.out.println("Postfix: "+ postfixStr);
                        System.exit(0);
                   else {
                        postfixStr += c;
    In the "help wanted" else-loop I want to do the following:
    The operator from stack should pop, and
    it must be compared with the next operator
    from the infix-expression, in according to the
    priority which is given in the opPri, infixPri and opStackPri.
    The if the infix-operator has a higher priority then I push it
    to the stack, else the stack-operator pops and are added
    to the postfix-string, and the next stack operator is popped and
    compared with the same infix-operator. Then again if the infix has
    a higher value I push it to the stack, else the stack-operator is popped
    and added. So on and so on...
    As you see, I know how it should function, but I am not sure at all
    about the syntax. Can anyone please help me with this?
    thanks!
    torvald helmer

    Hi there, firstly im not sure why u have done infixPri and opStackPri, i dont think those are necessary?? I have implemented an infix to postfix algorithm that uses only these operators : + - / *. From the help wanted part what you'd want to do is to do this: while the stack is not empty and a '(' character is not encountered, operators of greater or equal precedence from the stack will be popped then appended to the postfixExp else stop the while. Once the while is finished then u push infix onto the stack. Hope this helps. Cheers

  • Infix to Postfix, and evaluation

    Hi,
    Right now I'm coding a program that transforms a string representing an infix expression (a+b) to a string result that represents the same expression but in postfix notation (a b +) and then evaluates it. The only difficulty is that I'm not using java, I'm requested to use PCSpim which is an assembly language. Could anybody help me by referrencing me to an algorithm, please note that assembly language is a low level language, therefore, structures are not defined, but can be simulated and registers are limited...
    Even better, if you know of any url that contains PCSpim codes, please let me know...
    thanks,
    Alessandro.

    The result was
    a 10k (that's another advantage of programming in
    assembly language) file which runs very fast. I
    recommend assembly language for operations that
    require speed! and Java for anything you wish!.That's true but what happens to portability. To move your program to some other platform you face writing a 10k assembly program (for a processor you may know nothing about). I think you should use assembly only as a last resort, and carefully consider if you really need that speed.

  • Infix to Postfix calculation: having problems.. help?

    This is a program that when you input infix expression, it converts it to postfix expressions the evaluates the postfix..
    I'm having difficulty in my main method. How do i loop it? when the user wants to another input an expression?..
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    public class Calculator {
         private static Stack operators = new Stack();
         private static Stack operands = new Stack();
         private static int precedence( char operator ) {
              if (operator == '+' || operator == '-' )
                 return 1;
              else if (operator == '*' || operator == '/' || operator == '%')
                  return 2;
              return 0;
         private static String convertToPostfix( String infix ) {
         StringTokenizer input = new StringTokenizer( infix );
         String symbol;
         String postfix = "";     
         while (input.hasMoreTokens()) {          
             symbol = input.nextToken();     
              if (Character.isDigit(symbol.charAt(0))){
                  postfix = postfix + " " + (Integer.parseInt(symbol));     
              }else if (symbol.equals("(")){ 
                   Character isOperator = new Character('(');
                   operators.push( isOperator );
              }else if (symbol.equals(")")) {
                   while (((Character)operators.peek()).charValue() != '(') {
                       postfix = postfix + " " + operators.pop();
                   }operators.pop();
              } else {
                   while (!operators.empty() && !(operators.peek()).equals("(") && precedence(symbol.charAt(0)) <= precedence(((Character)operators.peek()).charValue()))
                        postfix = postfix + " " + operators.pop();
                        Character isOperator = new Character(symbol.charAt(0));
                        operators.push( isOperator );
              while (!operators.empty())
                   postfix = postfix + " " + operators.pop();
                        return postfix;
         private static int evaluate( String postfix ) {
         StringTokenizer input2 = new StringTokenizer( postfix );
         int value;
         String symbol;
         while (input2.hasMoreTokens()) {
             symbol = input2.nextToken();
              if (Character.isDigit(symbol.charAt(0))) {
                  Integer isOperand = new Integer(Integer.parseInt(symbol));
                   operands.push( isOperand );
              }else{
                   int op2 = ((Integer)operands.pop()).intValue();
                   int op1 = ((Integer)operands.pop()).intValue();
                   int result = 0;
                        switch(symbol.charAt(0)){
                             case '*': result = op1 * op2;
                                            break;
                             case '+': result = op1 + op2;
                                            break;
                             case '-': result = op1 - op2;
                                            break;
                             case '/': result = op1 / op2;
                                            break;
                             case '%': result = op1 % op2;
                                            break;
                        Integer isOperand = new Integer(result);
                        operands.push( isOperand );
              value = ((Integer)operands.pop()).intValue();
              return value;
         public static void main(String args[]) throws IOException {
                     JOptionPane.showMessageDialog(null,  "Hello user! I hope you have a wonderful time using the
                        calculator.  = ]"  , "Welcome", JOptionPane.PLAIN_MESSAGE);     
                  JOptionPane.showMessageDialog(null,  "Note: Enter Infix expressions with spaces in between.",
                        "Welcome", JOptionPane.PLAIN_MESSAGE);
                  String infix = JOptionPane.showInputDialog("Enter Mathematical Expression Here: ");
                  String output = "The expression in Postfix is: " +  convertToPostfix(infix);
                  JOptionPane.showMessageDialog(null, output);
                  String answer = "The answer to the equation:  " + evaluate(convertToPostfix(infix));
                  JOptionPane.showMessageDialog(null, answer);
                       String options[] = {"Yes","No",}
                   int option = JOptionPane.showOptionDialog(null,"Do you want evaluate an expression?", "Calculator",  
                       JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,options,options[0]); 
                  JOptionPane.showMessageDialog(null,  "Thank you for using the calculator.\n Have a nice day!  = ]");
    }

    Don't waste people's time by posting your question in more than one forum, please.
    Continued here: [http://forums.sun.com/thread.jspa?threadID=5333073]

  • Infix to Postfix application

    I have to check if the input message is balanced ( only () [] {} ) then i have to check anothe rinput message and make sure its infix, then convert it to postfix, and thats where my problem is, i seem to have everything, but i cant get around this SyntaxErrorException, im not sure how to get it to work, i feel like im missing a very small part, any ideas ? The catch block with the syntaxerrorexception cannot find the symbol, and yes it is already defined in another class,
    import java.util.*;
    import java.util.Stack;
    import java.util.EmptyStackException;
    import javax.swing.JOptionPane;
    public class ParentheseApp {
    public static void main(String args[])     {
    String newText = JOptionPane.showInputDialog("Enter a Mathematical expression");
    ParenChecker theParenthese = new ParenChecker();
    oolean test = theParenthese.isBalanced(newText);          
    if (test = true) {
    /IF public STATIC boolean was not called in the parenchecker
    //class then i would have to call the method
    if(ParenChecker.isBalanced(newText)) {
    JOptionPane.showMessageDialog(null, newText + "is balanced");
         else
    JOptionPane.showMessageDialog(null, newText + "is not balanced");
    String infix = JOptionPane.showInputDialog("Eneter an infix expression");
    InfixToPostfixParens theIntoPost = new InfixToPostfixParens();
    if(ParenChecker.isBalanced(infix)) {
    JOptionPane.showMessageDialog(null, infix + "is balanced");
         else
    JOptionPane.showMessageDialog(null, infix + "is not balanced");
         while(ParenChecker.isBalanced(infix)) {
    JOptionPane.showMessageDialog(null, infix + "is balanced");
              try {
         String postfix = theIntoPost.convert(infix);
    JOptionPane.showMessageDialog(null, "Infix expression " +
         infix + "converts to" + postfix);
    catch (SyntaxErrorException e) {
    JOptionPane.showMessageDialog(null, e.getMessage());
              }

    wpafbuser1 wrote:
    huh? balanced? infix? care to elaborate on these?I believe infix refers to infix notation: "(a + b) * c". Postfix would be "a b + c *". Balancing would be whether the parentheses in the infix notation are matched.
    However, there's no code of any significance to this problem in OP's post.
    EDIT: I think postfix is sometimes called RPN (reverse polish notation).
    Edited by: paul.miner on Dec 13, 2007 3:14 PM

  • Infix to PostFix

    hi,
    I have an infix format as shown below, i need to know how does this logical infix expression can be converted in to postfix expression.
    How do v specify the IF THEN ELSE of the expression in the postfix expression.
    IF:VarX :> :123 :THEN :VarY := :234 :+ :VarSAM :EIF
    Thanks in advance..

    the question as you have asked it has no answer. It is a bit like saying, "I want to travel to a foreign land, How do you say 'Hello'"
    The problem is that you have not specified any language.
    In-fix and post-fix simply refer to two different ways of writing out trees (and the use of the term 'infix' strongly implies binary trees at that). In post fix you ouput the value of a parent only after you have output the value of the children of that parent. In in fix you output the parent inbetween its two children (hence the implication of binary trees)
    In the world of mathematical expressions, like you learn in algebra and calculus, there is a well defined and commonly understood structure (that also just happens to be binary for the four main operation +,-,*,/) So it is easy to talk about taking the expression:
    6 + 3*(7 - 5)
    and talk about the postfix form:
    6 3 7 5 - * +
    However when you are talking about parsing a computer expression, you are now talking about general trees and there are numerous different ways that you could structure those trees.
    For example you could think of an IF as a 3 way branching node like this
    IF(boolean, code1, code2)
    or if you want to be binary about it you introduce a new branch node
    IF(boolean, CodePair( code1, code2))
    But nothing prevents you from doing any other wierd thing like perhaps
    ELSEIF( code2, SimpleIF(boolean, code1))
    Needless to say all of these representation are equally valid and all have completely different post fix representations.
    Since you have not defined any underlying tree structure for the code in your example it is not possible to give an answer.
    If your little infix example was in fact derived from a grammer, then you must go back and look at the tree structure that was implied by your grammer and then you could possibly talk meaningfully about a post fix representation of the parse.
    Hope that helps

  • Infix to Postfix Converter

    Hello,
    I have the following code and it works fine. The converter works correctly but only if there is a space between the characters; therefore, it can't handle inputs with multiple digits (e.g., 34).
    How can I modify this code so that there does not have to be a space between each character.
    Example:
    Currently the program will only run if there is a space between input character. Example: ( 5 * 2 ) / ( 2 * 1 )
    However, the program should be able to handle expressions like: (300+23)*(43-21)/(84+7) -- see, with multiple digit numbers like 300
    Thank you.
    import java.io.*;
    import java.util.*;
    import javax.swing.JOptionPane;
    public class ExpressionEvaluator
         // initialize two stacks: operator and operand
         private static Stack operatorStack = new Stack();
         private static Stack operandStack = new Stack();
         // method converts infix expression to postfix notation
         private static String toPostfix(String infix)
              StringTokenizer s = new StringTokenizer(infix);
              // divides the input into tokens for input
              String symbol, postfix = "";
              while (s.hasMoreTokens())
              // while there is input to be read
                   symbol = s.nextToken();
                   // if it's a number, add it to the string
                   if (Character.isDigit(symbol.charAt(0)))
                        postfix = postfix + "" + (Integer.parseInt(symbol));
                   else if (symbol.equals("("))
                   // push "("
                        Character operator = new Character('(');
                        operatorStack.push(operator);
                   else if (symbol.equals(")"))
                   // push everything back to "("
                        while (((Character)operatorStack.peek()).charValue() != '(')
                             postfix = postfix + " " + operatorStack.pop();
                        operatorStack.pop();
                   else
                   // print operatorStack occurring before it that have greater precedence
                        while (!operatorStack.empty() && !(operatorStack.peek()).equals("(") && prec(symbol.charAt(0)) <= prec(((Character)operatorStack.peek()).charValue()))
                             postfix = postfix + " " + operatorStack.pop();
                        Character operator = new Character(symbol.charAt(0));
                        operatorStack.push(operator);
              while (!operatorStack.empty())
                   postfix = postfix + " " + operatorStack.pop();
              return postfix;
         // method evaulates postfix expression
         private static int evaluate(String postfix)
              StringTokenizer s = new StringTokenizer(postfix);
              // divides the input into tokens for input
              int value;
              String symbol;
              while (s.hasMoreTokens())
                   symbol = s.nextToken();
                   if (Character.isDigit(symbol.charAt(0)))
                   // if it's a number, push it onto stack
                        Integer operand = new Integer(Integer.parseInt(symbol));
                        operandStack.push(operand);
                   else // if it's an operator, operate on the previous two popped operandStack items
                        int op2 = ((Integer)operandStack.pop()).intValue();
                        int op1 = ((Integer)operandStack.pop()).intValue();
                        int result = 0;
                        switch(symbol.charAt(0))
                             case '*': {result = op1 * op2; break;}
                             case '+': {result = op1 + op2; break;}
                             case '-': {result = op1 - op2; break;}
                             case '/': {result = op1 / op2; break;}
                             case '%': {result = op1 % op2; break;}
                        Integer operand = new Integer(result);
                        operandStack.push(operand);
              value = ((Integer)operandStack.pop()).intValue();
              return value;
         // method compares operators to establish precedence
         private static int prec(char x)
              if (x == '+' || x == '-')
                   return 1;
              if (x == '*' || x == '/' || x == '%')
                   return 2;
              return 0;
         public static void main(String args[]) throws IOException
              String infix;
              // Enter an infix equation option
              infix = JOptionPane.showInputDialog(null, "Enter an Infix Expression:");
              // displays the postfix answer
              JOptionPane.showMessageDialog(null, "Converted to a Postfix Expression: " + toPostfix(infix));
              // Evaluates the expression
              JOptionPane.showMessageDialog(null, "The answer is: " + evaluate(toPostfix(infix)));
    }

    babypurin wrote:
    Currently the program will only run if there is a space between input character. Example: ( 5 * 2 ) / ( 2 * 1 )However, the program should be able to handle expressions like: (300+23)*(43-21)/(84+7) -- see, with multiple digit numbers like 300... I'm still working on an actual answer... I just thought I'd "fix" the question with some strategically placed code tags... The dratted forum software uses common arithmetic operators as markup, which (IMHO) causes a lot more trouble than it's worth.

  • Infix to postfix printing out incorrectly sometimes..any ideas?

    alright, my program this time is to make an infix to postfix converter.
    I have it coded, and it works fine except when I use parenthesis. I'm supposed to test it with these expressions:
    a + b
    a * b + c
    a * ( b + c )
    a + b * c - d
    ( a + b ) * ( c - d )
    a - ( b - ( v - ( d - ( e - f ))))
         // initialize two stacks: operator and operand
         private Stack operatorStack = new Stack();
         private Stack operandStack = new Stack();
         // method converts infix expression to postfix notation
         public String toPostfix(String infix)
              StringTokenizer s = new StringTokenizer(infix);
              // divides the input into tokens for input
              String symbol, postfix = "";
              while (s.hasMoreTokens())
              // while there is input to be read
                   symbol = s.nextToken();
                   // if it's a number, add it to the string
                   if (Character.isDigit(symbol.charAt(0)))
                        postfix = postfix + " " + (Integer.parseInt(symbol));
                   else if (symbol.equals("("))
                   // push "("
                        Character operator = new Character('(');
                        operatorStack.push(operator);
                   else if (symbol.equals(")"))
                   // push everything back to "("
                        /** ERROR OCCURS HERE !!!! **/
                                 while (((Character)operatorStack.peek()).charValue() != '(')
                             postfix = postfix + " " + operatorStack.pop();
                        operatorStack.pop();
                   else
                   // print operatorStack occurring before it that have greater precedence
                        while (!operatorStack.isEmpty() && !(operatorStack.peek()).equals("(") && prec(symbol.charAt(0)) <= prec(((Character)operatorStack.peek()).charValue()))
                             postfix = postfix + " " + operatorStack.pop();
                        Character operator = new Character(symbol.charAt(0));
                        operatorStack.push(operator);
              while (!operatorStack.isEmpty())
                   postfix = postfix + " " + operatorStack.pop();
              return postfix;
    // method compares operators to establish precedence
         public int prec(char x)
              if (x == '+' || x == '-')
                   return 1;
              if (x == '*' || x == '/' || x == '%')
                   return 2;
              return 3;
    /** MY STACK **/
    import java.util.LinkedList;
    public class StackL {
      private LinkedList list = new LinkedList();
      public void push(Object v) {
        list.addFirst(v);
      public Object peek() {
        return list.getFirst();
      public Object pop() {
        return list.removeFirst();
      public boolean isEmpty()
          return (list.size() == 0);
    }weird, it erased my question/errors I put in...
    When I use any of the expressions with parenthesis (except the 2nd to last one) I get an emptystackexception pointing to the area noted in the code.
    When I test the 2nd to last one (the one I would expect it to give me the most trouble) it prints out an answer, but it is incorrect. It prints out this : "Expression in postfix: a ( b - ( c - ( d - ( e - f ) -" which is incorrect, as it hsould have no parenthesis
    Edited by: Taco_John on Apr 6, 2008 12:46 PM
    Edited by: Taco_John on Apr 6, 2008 12:47 PM
    Edited by: Taco_John on Apr 6, 2008 12:49 PM

    the algorithm we were told to use is here:
    While not stack error and not the end of infix expression
    a.) Extract the next input token from the infix expression (can be constant value, variable, arithmetic operator, left or right parenthesis)
    b.) If token is
    - left parenthesis : push it onto the stack
    - right parenthesis : pop and display stack elements until the left parenthesis is popped (don't sisplay right parenthesis). It's an error if stack becomes empty with no matching right parenthesis found.
    - Operator : if the stack is empty or token is higher priority than the top element, push it onto the stack. Otherwise, pop and display the top stack element and repeat comparison of token with new top element
    Note : left parenthesis in the stack is assumed to have a lower priority than any operator.
    - operand : display it
    When the end of the infix expression is reached, pop and display remaining stack elements until it is empty.
    it works fine on anything without a parenthesis, and it prints an answer (however it is incorrect) for the a - (b-(c-(d-(e-f)))) expression.
    still looking for an idea if I can get one
    Ok, I just noticed this. If i do a * ( b + c ) I get the error. But if I type " a * ( ( b + c ))" with spaces between the left parenthesis and adding an extra parenthesis as well, and NOT spacing the right parenthesis, I get a result that works just like that 2nd to last was doing. So it's something about the spaces...The answer is incorrect when I use the parenthesis as well. So it's not ignoring white space correctly for some reason and it's printing incorrect answers when I use parenthesis.

  • Infix Expression - Postfix Expressions

    Hello
    I have a program that uses 2 stacks (InfixStack and OperatorStack) to evaluate an infix expression that a user inputs. My problem is that i want to also output the postfix form of the infix expression, i know that i need another stack (PostfixStack). I don't know what the algorithm for converting Infix --> Postfix. I would appreciate any help regrading this matter, a description of the algorithum or psdeou code.
    Thanks

    Try these links:
    http://www.cs.uct.ac.za/courses/Course1/116/Tut0/help/inpostalg.html
    http://joda.cis.temple.edu/~koffman/cis223/InfixToPostfix.doc (MS Word DOC)
    This is a really nice paper in PDF:
    http://www.utdallas.edu/~vinod/publications/Prefix.pdf

  • Infix to postfix expression

    Hi all!
    I'm currently trying to finish up an assignment that is due in a few hours. Here's my delimma, according to the text book and the professor the following algorithm to convert an infix to postfix is as follows:
    1. Two stacks will be used in the conversion(expressionStack and operatorStack)
    2. if an operand is encountered, push onto expressionStack
    3. if an operator is encountered, including the "(" push onto the temporary stack
    4. if a ")" is encountered, pop each operator off the temporaryStack and push it into the expressionStack until a "(" is encountered in the temporaryStack. Once a "(" is encountered, pop that off the temporaryStack.
    Traverse through the infix expression until the end is reached then pop everything from the temporaryStack onto the expression stack.
    Here's the code I wrote for it:
    public String convertInfixToPostfix() throws PostfixConversionException {
      //if there is an unbalace set of parenthesis, throw exception
        if(!isBalance()) {
          throw new PostfixConversionException("Unable to convert infix expression");
        for(int i = 0; i < this.infixExpression.length(); i++) {
          char ch = this.infixExpression.charAt(i);
          //if ch is an operand, push onto stack
          switch(ch) {
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
            this.expressionStack.push("" + ch);
            break;
            //if ch is an operator or a '(', push onto temporaryOperator stack
            case '+':
            case '-':
            case '*':
            case '/':
            case '%':
            case '(':
              this.temporaryOperator.push("" + ch);
              break;
            /*if ch is ')' push all operators from temporaryOperator stack onto expressionStack until
             * until a matching '(' is encountered*/
            case ')':
              //while the top does not equal "(" pop everything off temporaryOperator stack and onto expression stack until a '(' is encountered
              while(!"(".equals(this.temporaryOperator.top())) {
                this.expressionStack.push(this.temporaryOperator.pop());
              //removes one open matching '('
              this.temporaryOperator.pop();
              break;
            default:
              System.out.println("Unable to converted due to invalid characters entered");
              break;
        //while expressionStack is not empty, push everything into temporaryOperator stack
        while(!this.expressionStack.isEmpty()) {
          this.temporaryOperator.push(this.expressionStack.pop());
        while(!this.temporaryOperator.isEmpty()) {
          this.postfixExpression = this.postfixExpression + this.temporaryOperator.pop();
        return this.postfixExpression;
      }The problem is, unless I did the code wrong (which I don't think i did), the method incorrectly converts the infix to the postfix expression. Meaning the algorithm provided by the text book and professor is incorrect. Are there other ways of converting an infix to postfix expression?

    Well using 2 stacks is same as 1 stack and 1
    StringBuffer. So I'd get rid of your temporary stack.
    Tokens either get pushed onto the operator stack or
    postfix stack.I wish I could get rid of the temporary stack and use a StringBuffer, but the professor wants two stacks used.
    Brackets are only slightly more difficult. If you
    have opening bracket, simply push it onto the
    operator stack. If you have a closing bracket pop
    tokens off the operator stack onto the postfix stack
    until you encounter an opening bracket then you
    simply pop it off the stack and discard it.So basically what you're saying is exactly what my code is doing, only with two stacks. However it only works if the infix entered has to do only one operations like 4-8 or 8+3, etc..but when it converts a longer expression like 0-(((7-8+3*(9/1)*2)+5)*6), postfix is 078391/2**-56*- and result is 300. but when I entered the infix in a calculator, the result is -384. I check my compute method and Im pretty sure that is correct. So that leaves the conversion method. In any case heres the compute method, I might be wrong, but I'm pretty sure I got that down.
    1. when a operand is encountered, push it into stack
    2. when an operator is encountered, pop two operands off and compute, then push it back into the stack.
    public double computeResult(String postfix) throws PostfixArithmeticException {
        //local variables
        Stack computePostfix = new Stack();
        int countOperators = 0;
        int countOperands = 0;
        //goes through the postfix and determines number of operators and operands
        for(int i = 0; i < postfix.length(); i++) {
         char ch = postfix.charAt(i);
         if(ch == '+' || ch == '-' || ch == '*' || ch == '/' || ch == '%') {
           countOperators++;
         else
           countOperands++;
        //test if there are enough operators and operands, number of operators should be 1 less than operands
        if((countOperators + 1) != countOperands || postfix.length() == 1) {
          //throw PostfixArithmeticException if there are not enough operators or operands
          throw new PostfixArithmeticException("Unable to compute postfix expression.");
        //otherwise, compute postfix expresstion
        for(int i = 0; i < postfix.length(); i++) {
          char ch = postfix.charAt(i);
          //if the character is not a operator, push onto a stack
          if(ch != '+' && ch != '-' && ch != '*' && ch != '/' && ch != '%') {
            computePostfix.push("" + ch);
          //otherwise, if an operator, pop two operands off the stack, compute with operator and push back on stack
          else {
            double operand2 = Double.parseDouble("" + computePostfix.pop());
            double operand1 = Double.parseDouble("" + computePostfix.pop());
            switch(ch){
              case '+':
                this.result =  operand1 + operand2;
                break;
              case '-':
                this.result =  operand1 - operand2;
                break;
              case '*':
                this.result =  operand1 * operand2;
                break;
              case '/':
                this.result =  operand1 / operand2;
                break;
              case '%':
                this.result =  operand1 % operand2;
                break;
            computePostfix.push("" + result);
        //return the result of the computation
        this.result = Double.parseDouble("" + computePostfix.pop());
        return result;
      }Also, I've tested that there should be the correct number of operators to an operand (which is the number of operators is always one less than number of operands)

Maybe you are looking for