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)

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*++++
    */

  • 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 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

    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.

  • Postfix Expressions Problem

    I wrote a program for my AP Comp Sci A class that takes a postfix expression (e.g. 32+) and converts it into an infix expression (e.g. 3+2) and then solves it. It worked before I converted it into the 'solve' method, but now I did (because its required), it keeps giving me an EmptyStackException on the line "if(comparingyay.compareTo("+")==0)
                         stk.push(stk.pop()+stk.pop());"
    If anyone can help me debug this, I would be forever greatful.
    import java.util.*;
       import java.io.*;
        public class PostfixExpressions                                                                                                                             
           public static void main(String[] args)
             Scanner scan=new Scanner(System.in);
             String in=scan.next();
             int answer=solve(in);
             System.out.println(answer);
           public static int solve(String y)
             Stack<Integer> stk= new Stack<Integer>();
             for(int x=0;x<y.length();x++)
                char chars1=y.charAt(x);
                if(Character.isLetterOrDigit(chars1))
                   Integer ints=new Integer(0);
                   stk.push(ints.valueOf(y.substring(x,x+1)));
                String comparingyay=y.substring(x,x+1);
                if(comparingyay.compareTo("+")==0||comparingyay.compareTo("-")==0||
                   comparingyay.compareTo("*")==0||comparingyay.compareTo("/")==0)
                   if(!stk.isEmpty())
                      if(comparingyay.compareTo("+")==0)
                         stk.push(stk.pop()+stk.pop());
                      else if(comparingyay.compareTo("-")==0)      
                         int b=stk.pop();
                         int a=stk.pop();
                         stk.push(a-b);
                      else if(comparingyay.compareTo("/")==0)
                         int b=stk.pop();
                         int a=stk.pop();
                         stk.push(a/b);
                      else if(comparingyay.compareTo("*")==0)
                         stk.push(stk.pop()*stk.pop());
             return stk.pop();
       }

    You don't check for the number of elements in your stack, you just check whether it's empty and, if not, pop 2 elements (though it might be only 1) off it.
    Your program looks rather C-ish; equality checking on Strings is done via equals(), compareTo() is, uhm, unconventional. Though you don't need to check Strings at all while you have chars1.
    The Integer conversion part could be done this way:
    stk.push(new Integer(chars1 - '0'));Edit: apart from these comments, your program works for me with the input "32+".

  • Infix to Postfix - Please help

    Hello everybody...i am new in java...and i thing i messed up with my exercise. Can anyone help? I have to prepare a main class that translates infixes to postfixes. i have done this until now:
    import java.util.*;
    import jss2.*;
    import java.io.IOException;
    import java.util.Stack;
    public class a3
         private Stack theStack;
         private String input;
         private String output = "";
         public a3(String in)//Constructor for a3 class
         String input = in;
         int stackSize = input.length();
         theStack = new Stack(stackSize);
         public static void main(String[] args) throws IOException
         String input = "1+2*4/5-7+3/6";
         String output;
         System.out.println("- The program translates the InFix to PostFix");
         System.out.println("- The format that you have to enter is: ");
         System.out.printf("(X+Y)*(Z-I) or similar expressions with numbers");
         System.out.println();
         a3 Trans = new a3(input);
         output = Trans.Postfix();
         System.out.println("Postfix is " + output + '\n');
    i have entered in the same package the classes: Postfix.java, LinkedStack.java, PostfixEvaluator.java and StackADT.java
    Please can anyone help me somehow??????

    Please have a look here
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=5217005
    and here
    http://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-postfix/index.htm
    for a general explanation of the algorithm you need.
    Also, when posting your code, please use code tags so that your code will be well-formatted and readable. To do this, either use the "code" button at the top of the forum Message editor or place the tag &#91;code&#93; at the top of your block of code and the tag &#91;/code&#93; at the bottom, like so:
    &#91;code&#93;
      // your code block goes here.
    &#91;/code&#93;Other sites to look at:
    http://forum.java.sun.com/thread.jspa?forumID=54&threadID=5157105
    http://forum.java.sun.com/thread.jspa?forumID=31&threadID=778333
    http://onesearch.sun.com/search/onesearch/index.jsp?charset=utf-8&col=community-all&qt=infix+postfix&y=0&x=0&cs=false&rt=true
    ps: don't pay bogad, he's a cheating sob and will rob you blind. We'll help you here for free.
    good luck, pete
    Edited by: petes1234 on Nov 10, 2007 11:40 AM

  • Convert infix to postfix

    i need a reply fast... i have been trying to convert infix to post fix in java.... but i cant get the output. The program just print the same input....i cant get output
    heres my code
    import java.util.Scanner;
    import java.io.*;
    import java.util.*;
    public class Infix{
         public static void main( String[] args){
              Scanner scan=new Scanner(System.in);
              Stack<String> stack = new Stack<String>();
              System.out.println(" enter infix");
              String s=scan.next();
              while (!s.equals(0)){
                   String postfix="";
                   if ( s.equals("+")) stack.push(s);
                   else if ( s.equals("-")) stack.push(s);
                   else if ( s.equals("*")) stack.push(s);
                   else if ( s.equals("/")) stack.push(s);
                   else if ( s.equals("(")) System.out.print("");
                   else if ( s.equals(")")) System.out.print(stack.pop()+"");
                   System.out.println("postfix");
                   //System.out.print(s);// I DONT KNOW HOW TO ADD ALL THE VARIABLES INTO A SEPERATE STRING
         System.exit(1);
    Edited by: boygenius on Sep 16, 2007 3:04 PM

    http://scriptasylum.com/tutorials/infix_postfix/algorithms/infix-postfix/index.htm
    I have found the above site has a great explanation of how to perform the conversion. Basically you will need a Stack to push/pop your operators as well as a String/StringBuffer/StringBuilder to build the postfix expression.

  • Recursive Infix to Postfix algorithm (Shunting-yard algorithm)

    Hi, I have to write a Infix to Postfix algorithm in a recursive form. I have an idea of how to do it iteratively using a Stack, but recursively I'm having some trouble. Could anybody offer some help or hints on how to get started?

    Well, I could write the iterative version along the lines of this:
    Scanner inScan = new Scanner(System.in);
    String exp;
    StringBuffer postfix = new StringBuffer();
    Stack stk = new Stack<Character>();
    System.out.println("Enter an arithmetic expression: ");
    exp = inScan.nextLine();
    for(int i = 0; i<exp.length(); i++)
        char ch = exp.charAt(i);
        if(ch<='F' && ch>='A')
            stk.push(ch);
        else{
           switch(ch)
              case '+':       \\what to do if ch is a + operator
              case '*':        \\what to do if ch is a * operator
              case '(':        \\what to do if ch is a (
              // and so on for each operator or paranthesis, i know what to do with each operator
    }That's not the full program obviously and may have some mistakes, but I'm confident I know how to do it iteratively. Recursively is the problem. What kind of base case could I use for my recursive method? And do I need more than one recursive method?

  • Using a Switch statement for Infix to Prefix Expressions

    I am stuck on the numeric and operator portion of the switch statement...I have the problem also figured out in an if/else if statement and it works fine, but the requirements were for the following algorithm:
    while not end of expression
    switch next token of expression
    case space:
    case left parenthesis:
    skip it
    case numeric:
    push the string onto the stack of operands
    case operator:
    push the operator onto the stack of operators
    case right parenthesis:
    pop two operands from operand stack
    pop one operator from operator stack
    form a string onto operand stack
    push the string onto operand stack
    pop the final result off the operand stack
    I know that typically case/switch statement's can only be done via char and int's. As I said I am stuck and hoping to get some pointers. This is for a homework assignment but I am really hoping for a few pointers. I am using a linked stack class as that was also the requirements. Here is the code that I have:
       import java.io.*;
       import java.util.*;
       import java.lang.*;
    /*--------------------------- PUBLIC CLASS INFIXTOPREFIX --------------------------------------*/
    /*-------------------------- INFIX TO PREFIX EXPRESSIONS --------------------------------------*/
        public class infixToPrefix {
          private static LinkedStack operators = new LinkedStack();
          private static LinkedStack operands = new LinkedStack();
            // Class variable for keyboard input
          private static BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
             // Repeatedly reads in infix expressions and evaluates them
           public static void main(String[] args) throws IOException {
          // variables
             String expression, response = "y";
          // obtain input of infix expression from user
             while (response.charAt(0) == 'y') {
                System.out.println("Enter a parenthesized infix expression.");          // prompt the user
                System.out.println("Example: ( ( 13 + 2 ) * ( 10 + ( 8 / 3 ) ) )");
                System.out.print("Or as: ((13+2)*(10+(8/3))):  ");
                expression = stdin.readLine();     // read input from the user
             // output prefix expression and ask user if they would like to continue          
                System.out.println("The Prefix expression is: " + prefix(expression));     // output expression
                System.out.println("Evaluate another? y or n: ");          // check with user for anymore expressions
                response = stdin.readLine();     // read input from user
                if (response.charAt(0) == 'n') {          // is user chooses n, output the statement
                   System.out.println("Thank you and have a great day!");
                }     // end if statement
             }     // end while statement
          }     // end method main
       /*------------- CONVERSION OF AN INFIX EXPRESSION TO A PREFIX EXPRESSION ------------*/ 
       /*--------------------------- USING A SWITCH STATEMENT ------------------------------*/
           private static String prefix(String expression) {
                // variables
             String symbol, operandA, operandB, operator, stringA, outcome;
               // initialize tokenizer
             StringTokenizer tokenizer = new StringTokenizer(expression, " +-*/() ", true);     
             while (tokenizer.hasMoreTokens()) {
                symbol = tokenizer.nextToken();     // initialize symbol     
                switch (expression) {
                   case ' ':
                      break;     // accounting for spaces
                   case '(':
                      break;     // skipping the left parenthesis
                   case (Character.isDigit(symbol.charAt(0))):      // case numeric
                      operands.push(symbol);                                   // push the string onto the stack of operands
                      break;
                   case (!symbol.equals(" ") && !symbol.equals("(")):     // case operator
                      operators.push(symbol);                                             // push the operator onto the stack of operators
                      break;
                   case ')':
                      operandA = (String)operands.pop();     // pop off first operand
                      operandB = (String)operands.pop();     // pop off second operand
                      operator = (String)operators.pop();     // pop off operator
                      stringA = operator + " " + operandB + " " + operandA;          // form the new string
                      operands.push(stringA);
                      break;
                }     // end switch statement
             }     // end while statement
             outcome = (String)operands.pop();     // pop off the outcome
             return outcome;     // return outcome
          }     // end method prefix
       }     // end class infixToPrefixAny help would be greatly appreciated!

    so, i did what flounder suggested:
             char e = expression.charAt(0);
             while (tokenizer.hasMoreTokens()) {
                symbol = tokenizer.nextToken();     // initialize symbol     
                switch (e) {
                   case ' ':
                      break;     // accounting for spaces
                   case '(':
                      break;     // skipping the left parenthesis
                   case '0':
                   case '1':
                   case '2':
                   case '3':
                   case '4':
                   case '5':
                   case '6':
                   case '7':
                   case '8':
                   case '9':
                      operands.push(symbol);     // push the string onto the stack of operands
                      break;                               // case numeric
                   case '+':
                   case '-':
                   case '*':
                   case '/':
                      operators.push(symbol);     // push the operator onto the stack of operators
                      break;                               // case operator
                   case ')':
                      operandA = (String)operands.pop();     // pop off first operand
                      operandB = (String)operands.pop();     // pop off second operand
                      operator = (String)operators.pop();     // pop off operator
                      stringA = operator + " " + operandB + " " + operandA;          // form the new string
                      operands.push(stringA);
                      break;
                   default:
                }     // end switch statement
             }     // end while statement
             outcome = (String)operands.pop();     // pop off the outcome
             return outcome;     // return outcomeafter this, I am able to compile the code free of errors and I am able to enter the infix expression, however, the moment enter is hit it provides the following errors:
    Exception in thread "main" java.lang.NullPointerException
         at LinkedStack$Node.access$100(LinkedStack.java:11)
         at LinkedStack.pop(LinkedStack.java:44)
         at infixToPrefix.prefix(infixToPrefix.java:119)
         at infixToPrefix.main(infixToPrefix.java:59)
    Any ideas as to why? I am still looking through seeing if I can't figure it out, but any suggestions? Here is the linked stack code:
        public class LinkedStack {
       /*--------------- LINKED LIST NODE ---------------*/
           private class Node {
             private Object data;
             private Node previous;
          }     // end class node
       /*--------------  VARIABLES --------------*/
          private Node top;
      /*-- Push Method: pushes object onto LinkedStack --*/     
           public void push(Object data) {
             Node newTop = new Node();
             newTop.data = data;
             newTop.previous = top;
             top = newTop;
          }     // end function push
       /*--- Pop Method: pop obejct off of LinkedStack ---*/
           public Object pop()      {
             Object data = top.data;
             top = top.previous;
             return data;
          }     // end function pop
       } // end class linked stackEdited by: drmsndrgns on Mar 12, 2008 8:10 AM
    Edited by: drmsndrgns on Mar 12, 2008 8:14 AM
    Edited by: drmsndrgns on Mar 12, 2008 8:26 AM

  • Sample progran of converting infix to postfix

    greetings to each and everyone of us..i need help about my problem in data structures. i need samples of converting infix to postfix.if u have any ideas regarding dis matter plz do reply me..thanks so much.

    What are you talking about?

  • Help! - code for infix to postfix

    can someome please send me the code for infix to postfix?
    thanks

    Or--and I know this will sound crazy, but just keep an open mind--you could try doing your homework yourself, and then post your attempt here when you get stuck, along with details of what specific problems you are having.
    If you are unwilling or unable to do that, then you should look elsewhere. This site is not a place to get code written for you. Try finding someone who will do it for money.

  • Code for infix to postfix

    plz send me infix to postfix code in java soon.

    plz send me infix to postfix code in java soon.I've intercepted all transmissions. Any code sent to
    you has been redistributed to various parts of the
    internet at random. You'll have to go find it
    yourself (using one of the common search engines).You forgot the "All your base are belong to us!" statement...

Maybe you are looking for

  • Notebook Lenovo V570c и Windows XP

    Здравствуйте , раз уж мне выпала честь открыть первой темой этот раздел. Имею ноутбук V570c В использовании в рабочих целях выявилась не обходимость пользоваться старыми программами и соотвественно к ним требуются старые ОС. Моя конкретно модификация

  • Blocking Goods Receipt for more than one PO

    Dear All,           We have a requirement. We do not want to do goods receipt for more than one PO.STD SAP is allowing us to do the same. Can we block it ? We want one One Material Doc for One PO .For One PO there can be more than one material docume

  • 2 iMacs sharing a Firewire Drive

    Is is possible to have my 2 iMacs share the same external Firewire drive via Firewire? I have an ethernet hub but it's not quite fast enough for what I need. I want both iMacs using the same hard drive thru firewire... thanks

  • Configuring WenSphere - SQL Server Datasource with IdM

    Hi All - I am trying to configure WebSphere (6.0) Datasource (for SQl Server2000) with IdM (7.0). and I am stuck at the step where we execute setRepo command to use the datasource. It was not able to find the WsnInitialContextfactory.class earlier. B

  • Breaking message processing for perticular message in Biztalk Orchestration.

    Hello All, In above Orchestration I need to break the process for particular incoming message if the decide condition get TRUE,  I also don't want to execute further shapes if condition is TRUE. I have tried using Terminate shape but it has stopped w